I’m trying to load file in texture2d with “UnityWebRequestTexture” in Awake().
Most of examples are loading textures with different async manner (with async or coroutine) but I don’t need such thing. Main goal is to get textures once, process them to create from them an array and use created array after that. So for me it is preferable to somehow load texture in sync way. What I understood with coroutine way I need some how check after that is texture where loaded and processed in Update, or creating some callbacks and split all loading process. It becomes a bit overcomplicated for my use case because in Update I don’t even need that textures, but only Arrays I got from processing them.
In fact I’m using UnityWebRequest only because it works same on PC and Android to get file from StreamingAssets.
To make in synchronous I tried the same approach as already using to get text files, by adding while(!www.IsDone) loop, but what can I see this freezes the game, and when trying debug it step by step I see that process enters in loop runs several cycles and seems crashes without error.
If I rewrite code with coroutines and delete loop everything works fine except I getting results somewhere in Update cycle, far away from place where I need them. Using downloadHandler’s isDone property changes nothing.
Main question is there some cross platform way to load texture synchronously with or without UnityWebRequestTexture
Ps I also tried using the just plain UnityWebRequest with plain downLoadHandler to get raw bytes and load them into texture, but in this case I don’t know beforehand dimensions of the texture. Also I tried to rewrite it as Async Tasks and add into cycle await sleep but got same error.
The code (there are some artifacts when I tried to rewrote it as coroutine)
private void GetTextureAndWaveData(string inPath, string inType, WaveZeroPosition inWaveZeroPosition)
{
float[] resultArray = null;
string path = $"{Application.streamingAssetsPath}{Path.DirectorySeparatorChar}{inPath}";
Texture2D resultTexture = null;
UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
www.SendWebRequest();
while (!www.downloadHandler.isDone) {
}
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log($" {inPath} |{www.error}");
throw new InvalidWaveInstrumentDataException($"no data:{inPath}");
}
else
{
resultTexture = DownloadHandlerTexture.GetContent(www);
resultArray = WaveForm.ReadTextureWaveToArray(resultTexture, inWaveZeroPosition, this.lineColorTreshold);
switch (inType) {
case "Wave": this.wave = resultArray; break;
case "FadeWave": this.fadeWave = resultArray; break;
case "FadeGain": this.fadeGain = resultArray; break;
}
}
}