问题描述
当我在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手册- https://docs.unity3d .com/Manual/StreamingAssets.html :
And Here is my try 2 - Based on Unity Manual - https://docs.unity3d.com/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加载无法在构建中使用,但可以在统一编辑器中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!