- Home /
How to make a helper function that returns a Texture2D from UnityWebRequest? (Android)
I am trying to update my helper function that loads images from the StreamingAssets folder into a Texture2D and then places that on a sprite, so that it works on Android builds. In my moderately large project, many different scripts in many different scenes call the following helper function to load their images from StreamingAssets. Below is the code that works perfectly fine for my build on Windows:
public static Texture2D LoadTexture(string filepath)
{
Texture2D texture = null;
if (File.Exists(filepath))
{
byte[] fileData = File.ReadAllBytes(filepath);
texture = new Texture2D(2, 2);
if (!texture.LoadImage(fileData)) Debug.LogError("Failed to read image texture from path: " + filepath);
}
else
Debug.LogError("Failed to find path to load Texture: " + filepath);
return texture;
}
I recently learned that StreamingAssets are stored in a .zip file on Android's storage, and consequently System.IO.File operations fail to operate on it. The solution is to use UnityWebRequest, as documented by Unity: https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTexture.html. My question is how to update this function so that it works within the context of a coroutine. I understand that you can use return values with a coroutine by sending it a System.Action parameter, as shown by harleywinks here: https://answers.unity.com/questions/24640/how-do-i-return-a-value-from-a-coroutine.html. Is the solution to place static references within the helper script to all of the Images/SpriteRenderers that rely on this function, or otherwise copy and paste the UnityWebRequest function into every UI script?
Answer by Spiros_Learity · Jul 30, 2019 at 10:32 PM
Well, someone spent the time to find a solution to reading streaming assets files on Android without coroutines/threading. Disappointing that such an important and frequently used feature has such poor support and native implementation. You can get the asset here: https://assetstore.unity.com/packages/tools/input-management/better-streaming-assets-103788
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Instantiating Prefabs on Android Mobile Not Working 3 Answers
How to use StreamingAssets folder on Android by using UnityWebRequest? 1 Answer
Android Sliding Controls 0 Answers