Hi,
I am trying to download an image from my website, but it doesn’t seem to be able to yield. I tried some things with coroutines and yield, but all ended up not working in C# script language. I use the following code for now, it’s called within “void Update()”:
void Update()
{
// Get the latest webcam shot from outside "Friday's" in Times Square
string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
// Wait for download to complete
RequestImage(url);
// assign texture
if(!isLoading)
imageRenderer.material.mainTexture = webDL.texture;
else
Debug.Log(webDL.isDone);
}
WWW webDL;
bool isLoading = false;
public void RequestAd(string url)
{
if(!isLoading)
{
webDL = new WWW(url);
isLoading = true;
}
if(isLoading webDL.isDone)
{
isLoading = false;
}
if(!webDL.isDone)
{
Debug.Log("Progress: " + webDL.progress);
}
}
I can’t seem to get the code from the WWW page working Unity - Scripting API: WWW
Any ideas?
“Note that you can’t use yield from within Update or FixedUpdate, but you can use StartCoroutine to start a function that can.”
http://unity3d.com/support/documentation/ScriptReference/index.Coroutines_26_Yield.html
So how would i solve this then? Cause i think my code is kinda lame this way…
But that still doesn’t really clarify for me how to use that in C#. I tried using this (psuedo):
function Update()
{
StartCoroutine(GetData("someurl"));
Renderer.material.mainTexture = [url]www.texture;[/url]
}
WWW www;
IEnumerator GetData(string URL)
{
www = new WWW(URL);
yield return www;
}
which a;ways gives me the error that the web content wasn’t downloaded yet before usage…
Call the coroutine from Start(), not from Update. Ignore Update. Don’t use update.
function Start()
{
StartCoroutine(GetData("someurl"));
}
IEnumerator GetData(string URL)
{
WWW www = new WWW(URL);
yield return www;
Renderer.material.mainTexture = [url]www.texture;[/url]
StartCoroutine(GetData("someurl"));
}
This will query the URL, wait until the texture is returned, updated the material, then automatically call it again. This is essentially what you were trying to do with Update, but instead just call the function again when it’s complete.
What Tempest suggest will work, but there really is no need to create a separate IEnumerator for that. Just make the Start method an IEnumerator and you’re good to go. An IEnumerator Start() will work the same way as function Start() in this case, only it will also allow the use of yield statements. This goes for C# as well.
In Unityscript(Javascript):
IEnumerator Start()
{
WWW www = new WWW("someurl");
yield return www;
Renderer.material.mainTexture = [url]www.texture;[/url]
StartCoroutine(Start());
}
Jens is correct except that you shouldn’t call StartCoroutine(Start()) from inside Start.