- Home /
Using WWW in public method of a GameObject in Unity C#
I am beginner in Unity3d and C# and after hours of searching solutions (and building a XML reader in C# based on documentation) I stuck on this problem:
I have two prefab planes tagged as "test" and I want to show images from URL on them as texture when the images loaded.
The planes has an empty Start and Update method and this public one in the loadImageFromURL.cs:
public IEnumerator changeTexture(string url){
Debug.Log (url);
WWW www = new WWW (url);
yield return www;
renderer.material.mainTexture = www.texture;
}
Then I have an empty gamobject that collects image URLs in the Start() method then I do this:
IEnumerator Start () {
WWW www = new WWW("http://example.com/xmlfile.rss");
yield return www;
stream = new StringReader(www.text);
/*Here I do all the XML stuff, it provides the URLs from the rss feed there is no error in it*/
picture = GameObject.FindGameObjectsWithTag("test");
loadImageFromURL sc = (loadImageFromURL)picture[0].GetComponent(typeof(loadImageFromURL));
//here I call the function
sc.changeTexture(URLs[2]);
}
When I simply pass the URL and just return null; in the changeTexture method it show the url when I Debug.Log it. When WWW lines are there it is like nothing happens. Also this exact same WWW code works perfectly as seen in Unity reference too
So I am pretty sure there is something I do not understand about WWW
Answer by frarees · Jan 12, 2014 at 03:25 PM
changeTexture
is an IEnumerator
method, so you have to call it using StartCoroutine
, otherwise it won't iterate properly. Try:
StartCoroutine (sc.changeTexture(URLs[2]);
Note that the coroutine will be started in that script not the reference. To start the coroutine in the other object, do something like:
sc.StartCoroutine (sc.changeTexture(URLs[2]);
Thank you very much, now I understand where and what I failed to understand in this. It works now.
Your answer
