【问题标题】:JSоn file is not readJSоn 文件未被读取
【发布时间】:2021-08-03 03:19:22
【问题描述】:

我在游戏中进行本地化,并将不同语言的单词写入 JSon 文件。在 Unity 编辑器中一切正常,但在 android 上它会抛出异常找不到文件!

 public void LoadLocalizedText(string langName)
    {

#if UNITY_ANDROID && !UNITY_EDITOR
                string path ="jar:file://" + Application.streamingAssetsPath + "/Languages/" + langName + ".json";
#else
        string path = Application.streamingAssetsPath + "/Languages/" + langName + ".json";
#endif

        if (File.Exists(path))
        {
            if (File.Exists(path))
            {
                string dataAsJson;

#if UNITY_ANDROID && !UNITY_EDITOR
          WWW reader = new WWW(path);
            UnityWebRequest unityWebRequest = new UnityWebRequest(path);
            while (!reader.isDone) { }
            dataAsJson = reader.text;
#else
                dataAsJson = File.ReadAllText(path);
#endif
                LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(dataAsJson);

                localizedText = new Dictionary<string, string>();
               
                for (int i = 0; i < loadedData.items.Length; i++)
                {
                    localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
                }

                currentLanguage = langName;
                isReady = true;

                OnLanguageChanged?.Invoke();
            }
            else
            {
                throw new Exception("Cannot find file!");
            }


        }

【问题讨论】:

  • 嗯,这并不奇怪(您会得到特定于环境的结果),您可以根据所使用的环境在不同的地方查看 (#if UNITY_ANDROID &amp;&amp; !UNITY_EDITOR)。我对 jar 文件 不熟悉,但我猜有一些工具可以让您查看它们以查看您要查找的文件是否在正确的位置
  • 在“ANDROID”和“UNITY EDITOR”上打印出“path”的值并进行比较。两者可能都解决了不同的值。您可以在两者的配置中设置基本路径并在代码中调用。
  • 系统路径一般使用Path.Combine

标签: c# json unity3d


【解决方案1】:

您不需要在 android 上为流媒体资源路径添加“jar:file//”。此外,如果您使用 android,您将不会通过 File.Exists(pass) 检查。 Here is the working exapmple.

【讨论】:

    猜你喜欢
    • 2015-06-08
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多