Unity List.Add 阻止 Android 上的精灵更新

Untiy List.Add prevents a sprite update on Android

我有一个在按下按钮时调用的方法,

private List<Page> _pages = new List<Page>();
public void LoadKern(int requestedKern)
    {
        TextAsset pages = Resources.Load("kern" + requestedKern) as TextAsset;

        JSONArray jsonPages = JSON.Parse(pages.text)["pages"].AsArray;

        foreach (JSONNode page in jsonPages)
        {
            _pages.Add(new Page(page["image"], page["text"]));
        }

        ImageSpriteRenderer.sprite = Resources.Load<Sprite>(_pages[currentPage].image);
        TextSpriteRenderer.sprite = Resources.Load<Sprite>(_pages[currentPage].text);
    }

代码在模拟器中 运行 时运行完美,但每当我将它部署到 android 设备或​​使用 Untiy Remote 4 它不再更新精灵。

每当我删除此行并手动设置资源时,它都会在按下按钮时更新。

_pages.Add(new Page(page["image"], page["text"]));

它在桌面上运行但在 Android 上运行似乎很奇怪,我是否遗漏了什么?

我觉得很难放在评论里,所以我把它写在这里作为答案。

验证由于 Resource.Load<> 引起的这个问题的最简单方法是添加以下代码:

TextAsset pages = Resources.Load("kern" + requestedKern) as TextAsset;
Debug.Load(pages + "are Loading");  // to see if it is really loaded successfully

连接您的设备并打开 adb 日志,使用 "are loading" 过滤消息。 如果您看到页面是 null,那么显然 Resource.Load<> 是罪魁祸首。

如果是Resource.Load<>的问题,可以考虑使用StreamingAssets:

Any files placed in a folder called StreamingAssets in a Unity project will be copied verbatim to a particular folder on the target machine. You can retrieve the folder using the Application.streamingAssetsPath property. It’s always best to use Application.streamingAssetsPath to get the location of the StreamingAssets folder, it will always point to the correct location on the platform where the application is running.

在 Android 上,您应该使用:

path = "jar:file://" + Application.dataPath + "!/assets/";

我怀疑你加载文字资源是在运行的时候进行的,当你打包app的时候,文字资源没有被读取,可能会被排除在项目之外,Unity是这样认为的"not used"。当您 运行 Android 上的应用程序时,它自然会失败。

使用 StreamingAssets 方法,您强制 Unity 复制文本资产 "verbatim",以确保它可以在 运行 时间访问!