我最终得到了以下解决方案。我没有找到加载原始文件主线程的方法,但我设法在协程中加载它并在后台线程上对该文件执行进一步(也是繁重的)操作。我做了一个这样的静态方法:
public static void ReadAllBytesInCoroutine(MonoBehaviour context, string filePath, Action<ReadBytesInCoroutineResult> onComplete)
{
context.StartCoroutine(ReadFileBytesAndTakeAction(filePath, onComplete));
}
private static IEnumerator ReadFileBytesAndTakeAction(string filePath, Action<ReadBytesInCoroutineResult> followingAction)
{
WWW reader = null;
try
{
reader = new WWW(filePath);
}
catch(Exception exception)
{
followingAction.Invoke(ReadBytesInCoroutineResult.Failure(exception));
}
while (reader != null && !reader.isDone)
{
yield return null;
}
followingAction.Invoke(ReadBytesInCoroutineResult.Success(reader.bytes));
}
ReadBytesInCoroutineResult 是我简单的自定义数据类:
public class ReadBytesInCoroutineResult
{
public readonly bool successful;
public readonly byte[] data;
public readonly Exception reason;
private ReadBytesInCoroutineResult(bool successful, byte[] data, Exception reason)
{
this.successful = successful;
this.data = data;
this.reason = reason;
}
public static ReadBytesInCoroutineResult Success(byte[] data)
{
return new ReadBytesInCoroutineResult(true, data, null);
}
public static ReadBytesInCoroutineResult Failure(Exception reason)
{
return new ReadBytesInCoroutineResult(true, null, reason);
}
}
这样我就有了一种机制可以在任何地方(只要它在主线程上)在协程中加载文件。同步加载文件,但由于协程,它没有阻塞主线程。后来我调用这个函数并在一个单独的线程上获取获取的字节,在那里我对它们执行繁重的计算。
ResourcesUtils.ReadAllBytesInCoroutine(monoBehavior, filePath, (bytes) => {
//here I run an async method which takes bytes as parameter
});