json加载无法在构建中使用,但可以在统一编辑器中使用

编程入门 行业动态 更新时间:2024-10-25 05:20:00
本文介绍了json加载无法在构建中使用,但可以在统一编辑器中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我在Android上构建时,我的json文件似乎未加载,因为我看不到数据.在统一编辑器中播放,效果很好.我正在努力在PC上运行某些东西,但在Android上却无法运行.我想这只是一条路径差异,但对于初学者来说并不容易.

When I build on Android my json files seems to not load because I dont see data. in unity editor play it works fine. I'm struggling with something thats working on PC but not on Android. Just a path difference I guess but its not easy for a beginner.

这是我的代码TRY 1:

here is my code TRY 1:

public static JsonData LoadFile(string path) { var fileContents = File.ReadAllText(path); var data = JsonMapper.ToObject(fileContents); return data; } public void QuestionLoader() { // Load the Json file and store its contents in a 'JsonData' variable var data = LoadFile(Application.dataPath + "/Resources/json/level1.json");

这是我的尝试2-基于Unity手册- docs.unity3d /Manual/StreamingAssets.html :

And Here is my try 2 - Based on Unity Manual - docs.unity3d/Manual/StreamingAssets.html:

public static JsonData LoadFile(string path) { var www = new WWW(path); return www.text; //var fileContents = File.ReadAllText(path); // var data = JsonMapper.ToObject(fileContents); // return data; } public void QuestionLoader() { string path = ""; // Load the Json file and store its contents #if UNITY_ANDROID path = "jar:file://" + Application.dataPath + "!/assets/Levels/level1.json"; #endif #if UNITY_EDITOR path = Application.dataPath + "/StreamingAssets/Levels/level1.json"; #endif // var data = LoadFile(path);

推荐答案

如果要从任何平台加载项目中已经存在的json,则有两个选择:

If you want to load json that already exist in the project from any platform, you have two options:

1 .将Json文件放在Resources文件夹中,然后使用Resources.Load读取为 TextAsset .例如,请参见此答案的结尾.

1.Put the Json file in the Resources folder then use Resources.Load to read it as a TextAsset. See the end of this answer for example.

2 .将json文件设置为AssetBundle,然后使用WWW.LoadFromCacheOrDownload进行加载.

2.Make the json file an AssetBundle then use WWW.LoadFromCacheOrDownload to load it.

其中任何一个都应该起作用.读取json文件后,您可以将其直接复制到Application.persistentDataPath,以便能够对其进行修改并在需要时进行保存.

Any of these should work. Once you read the json file, you can copy it to the Application.persistentDataPath directly so that you will be able to modify it and save it if needed.

更多推荐

json加载无法在构建中使用,但可以在统一编辑器中使用

本文发布于:2023-11-09 22:54:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:器中   加载   编辑   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!