【问题标题】:json load not working in build but works in unity editorjson 加载在构建中不起作用,但在统一编辑器中起作用
【发布时间】:2017-06-10 14:53:24
【问题描述】:

当我在 Android 上构建时,我的 json 文件似乎没有加载,因为我没有看到数据。在统一编辑器中运行良好。我正在为那些在 PC 上工作但在 Android 上不工作的东西苦苦挣扎。我猜只是路径差异,但对于初学者来说并不容易。

这是我的代码 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:

   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);

【问题讨论】:

    标签: c# android json unity3d


    【解决方案1】:

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

    1.将 Json 文件放入 Resources 文件夹,然后使用Resources.Load 将其读取为TextAsset。以this 答案结尾为例。

    2.将json文件制作成AssetBundle,然后使用WWW.LoadFromCacheOrDownload加载。


    其中任何一个都应该有效。读取 json 文件后,可以直接将其复制到Application.persistentDataPath,以便在需要时对其进行修改和保存。

    【讨论】:

    • 很好 - 感谢您的帮助
    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多