Android StreamingAssets loading files
Unity will have problems loading StreamAssets files in the android environment.
There are many solutions online
. Most of them involve the underlying Android to solve
the underlying methods
. Of course, Unity officially recommends using the UnityWebRequest class to access
UnityWebRequest .
However, the official method has a pain point. UnityWebRequest needs to use [Coroutine]
I found a solution using thread asynchronous
public static async Task<Stream> Reader(string path)
{
Stream fs = null;
UnityWebRequest request = UnityWebRequest.Get(path);
await request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError)
{
Debug.LogError("Read" + "/ERROR/" + request.error);
}
else
{
byte[] results = request.downloadHandler.data;
if (results.Length > 0)
{
fs = new MemoryStream(results);
}
}
return fs;
}
public static class ExtensionMethods
{
public static TaskAwaiter<object> GetAwaiter(this UnityWebRequestAsyncOperation op)
{
var tcs = new TaskCompletionSource<object>();
op.completed += (obj) =>
{
tcs.SetResult(null);
};
return tcs.Task.GetAwaiter();
}
}