Hi im trying to create a single object which is responsible for all downloading of textures a sort of proxy if you will (named TextureFetcher in the examples). All other objects who has textures can ask the TextureFecther to fecth a texture which they in turn can apply to their material.
The TextureFetcher code looks something like:
public class TextureFetcher : MonoBehaviour {
public Texture GetTexture(string url) {
Texture ret = null;
WWW www = new WWW(url);
if([url]www.error[/url] == null)
ret = [url]www.texture;[/url]
return ret;
}
}
Problem is this will not work (unless the url refers to a file on disk using the file:// syntax) as the texture is not garantueed to be completely downloaded when the next instruction executes (it probably has not even started downloading yet?). From what i read in the reference manual WWW should either be yielded in a coroutine or busy polled for IsDone().
I tried creating a Coroutine for the job to see if i could get the TextureFetcher to to work. Looks like:
public class TextureFetcher : MonoBehaviour {
public Texture GetTexture(string url) {
Texture ret = null;
StartCoroutine(DownloadTexture(url));
return ret;
}
public IEnumerator DownloadTexture(string url) {
WWW www = new WWW(url);
yield return www;
if([url]www.error[/url] == null) {
// Now the texture is downloaded!
[url]www.texture;[/url]
}
// can´t return texture here cause of IEnumerator return type.
}
}
Now the texture will be downloaded without busy polling, BUT i cannot make the method which started the download return the newly downloaded texture, so what to do next?
Make a private class variable set that from the coroutine when downloading has completed and return that.
public class TextureFetcher : MonoBehaviour {
private Texture m_texture = null;
public Texture GetTexture(string url) {
StartCoroutine(DownloadTexture(url));
return m_texture ;
}
public IEnumerator DownloadTexture(string url) {
WWW www = new WWW(url);
yield return www;
if([url]www.error[/url] == null) {
// Now the texture is downloaded!
m_texture = [url]www.texture;[/url]
}
}
}
This does also not work as StartCoroutine will return imediately after beeing called there by returning the value of the m_texture, which can be garantueed to be anything of the following: Null, the texture, garbage.
This is not what i want i want a garantuee that it is the texture complete or null if download fails.
So what todo? Well i could busy poll again :? so im back where i started.
Anyone have a viable solution to this problem?