I’m new to C# with Unity, but an expert Flash/AS3 developer…
I’m trying to call a function that will
- Load an image, and once loaded,
- Return the image.
The most common method for loading external files appears to be through yeilds on StartCoRoutines:
using UnityEngine;
using System.Collections;
public class TestScript : MonoBehaviour {
IEnumerator Start() {
yield return StartCoroutine( loadAsset("http://sm.local/some_image.png") );
}
IEnumerator loadAsset( string url ) {
WWW www = new WWW( url );
float elapsedTime = 0.0f;
while (!www.isDone) {
elapsedTime += Time.deltaTime;
if (elapsedTime >= 10.0f) break;
yield return null;
}
if (!www.isDone || !string.IsNullOrEmpty(www.error)) {
Debug.LogError("Load Failed");
yield break;
}
// load successful
Texture loadedTexture = www.texture;
}
}
That’s swell – except I want to reuse the loadAsset function to return multiple images. Something more like this:
IEnumerator Start() {
Texture image1 = yield return StartCoroutine( loadAsset("http://sm.local/some_image.png" ) );
Texture image2 = yield return StartCoroutine( loadAsset("http://sm.local/some_other_image.png" ) );
}
IEnumerator loadAsset( string url ){
WWW www = new WWW( url );
// ... yeild / error logic here
return www.texture;
}
But there appears to be no way to do this. There’s a hackier method to accomplish this by using a global variable for the returned value:
using UnityEngine;
using System.Collections;
public class TestScript : MonoBehaviour {
Texture returnedTextureFromLoadAsset;
IEnumerator Start() {
yield return StartCoroutine( loadAsset("http://sm.local/some_image.png" ) );
Texture image1 = returnedTextureFromLoadAsset;
yield return StartCoroutine( loadAsset("http://sm.local/some_image.png" ) );
Texture image2 = returnedTextureFromLoadAsset;
}
IEnumerator loadAsset( string url ){
WWW www = new WWW( url );
float elapsedTime = 0.0f;
while (!www.isDone) {
elapsedTime += Time.deltaTime;
if (elapsedTime >= 10.0f) break;
yield return null;
}
if (!www.isDone || !string.IsNullOrEmpty(www.error)) {
Debug.LogError("Load Failed");
yield break;
}
// load successful
returnedTextureFromLoadAsset = www.texture;
}
}
… but this seems very non-OOP.
Surely there is some method to have a CoRoutine return a value locally to the calling function.