c# - Android Unity - 在后台线程上加载文件

标签 c# unity3d

我需要在我的应用程序中加载一个文件,因为它很大(大约 250MB),我需要在主线程之外执行此加载。更何况,因为Android上的assets不是存放在一个普通的目录下,而是一个jar文件,所以我需要使用WWW或者UnityWebRequest类。

我最终得到了这样的辅助方法:

public static byte[] ReadAllBytes(string filePath)
{

    if (Application.platform == RuntimePlatform.Android)
    {
        var reader = new WWW(filePath);
        while (!reader.isDone) { }

        return reader.bytes;
    }
    else
    {
        return File.ReadAllBytes(filePath);
    }
}

问题是我不能在后台线程上使用它——Unity 不允许我在那里创建 WWW 对象。我如何创建这样的方法,它将读取当前线程上的那些字节?

最佳答案

只需将您的 while 循环放在 CoRoutine 中,当您的请求未完成时返回 yield 。完成后调用您要使用数据的方法:

IEnumerator MyMethod()
{
    var reader = new WWW(filePath);
    while (!reader.isDone) 
    { 
        yield return; // <- use endofFrame or Wait For ore something else if u want
    }
    LoadingDoneDoData(reader.bytes);
}

void LoadingDoneDoData(bytes[] data)
{
    // your Code here
}

关于c# - Android Unity - 在后台线程上加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54234452/

相关文章:

c# - 统一: How to save and load scenes according to player progress

c# - 如何替换 MeshRenderer.sharedMaterials 中的元素

c# - 如何修改 WebCamTexture 的大小?

unity3d - 每帧使用哪个公式进行拖动模拟?

java - 如何在 Java 测试框架中隐藏页面对象初始化

c# - 解析SQL查询并提取列名和表名

c# - Azure Functions V2 将 HttpRequest 反序列化为对象

c# - 更改场景时 WebCamTexture 崩溃

c# - 在 Silverlight 中设置 MultiScaleImage 控件的源

c# - 如何将时间跨度方法转换为十进制?