You don’t want the code to stall. If the code “stalls” your application will become nonresponsive. Your users (and the operating system) will think your game crashed until the file is done loading. What you want to do is take whatever you were going to do with the return value, and do it when the coroutine finishes. You could write another coroutine to wrap it:
IEnumerator LoadTextureAndDoSomething(string path) {
texzita = null;
// After this line, your texture will have been assigned
yield return StartCoroutine(LoadTextureRequest(path);
// Do something with the texture here.
}
Then start this coroutine also with StartCoroutine. Alternatively, you could add a callback function (probably an Action) as a parameter to LoadTextureRequest and invoke that function at the end of LoadTextureRequest.
Adding to what Praetor said above, the traditional way is to additionally supply a delegate that the coroutine calls to supply the texture to whoever wants it, or perhaps another delegate reporting whatever error it might have encountered.
I realize that you actually “intend” for that LoadTextureFromFile() to return a texture, but that just isn’t how modern software is best set up. Some resources are not always available instantly, so a function that asks for, waits and then returns the result is not practical in modern computing contexts.
Welcome to asynchronous programming! Here’s what it would look like to pass in a callback function:
public IEnumerator LoadTextureRequest ( string path, Action<Texture> callback) {
// all your code to get a texture with a web request goes here
Texture tex = DownloadHandlerTexture.GetContent(dlreq);
callback(tex);
}
thank you for the replies, is there any alternative way for me to get the texture instantly? Maybe without using unitywebrequest? And also without resources.load since i need a file from outside the project folder
I dont mind the non responsiveness in this case Im just loading the texture to store pixel data in a file. I was using resources.load but I need to get my resources folder out of the project so I just need something that can replace resources.load.
The closest is if you can open the target file using the System.IO hierarchy of calls, yes, you can do that substitution. But that won’t work for files on the net or anywhere else, just files present in your visible filesystem.
Another approach is to make your web requester load it, then write it to a temp file, then somewhere else your original code can just open it with the System.IO calls, once it has been signalled that it is ready.