- Home /
Coroutine needed here?
I'm a little confused. I have a routine that loads an object from a file (using WWW and yield), and after it's loaded, I want to modify the game object that it loads into.
What's the best way to do this?
What I have now looks something like this:
void MakeObjectFromFile (url) { GameObject newObj = GetObjectViaWWW (url); // returns a gameobject with the thing in it newObject.GetComponent(Collider).isTrigger = true; }
GameObject GetObjectViaWWW (url) { make a game object, various setup StartCoroutine(WaitForResponse(www)); }
public IEnumerator WaitForResponse(WWW www) { yield return www; // check for errors if (www.error == null) etc. }
If I understand correctly, GetObjectViaWWW will return immediately, so GetComonent(Collider) will probably fail because the coroutine is still just getting started.
I don't really want to do the post-processing in the WaitForResponse routine. Mainly, I haven't found a coding pattern I like for that, if one exists.
So is there one? Is there a preferred clean way of 'waiting for the operation to complete' when it's called in a subroutine like this? Should I set a semaphore and check it in an Update function or something?
It feels like I want to use a callback function. Which is sorta what a coroutine is, right? Can I pass a function into this somehow, essentially a callback from a callback?
You can wait for the completion of a coroutine use "yield return StartCoroutine();" But then you would need to change how you assign a reference to newObj, so it probably won't work as you need it to.
Answer by Mike 3 · Feb 13, 2011 at 11:47 AM
You can do something like this:
void MakeObjectFromFile (url) { //lambda version to do it inline GetObjectViaWWW (url, go=>go.GetComponent<Collider>.isTrigger = true); //or with a callback function GetObjectViaWWW (url, ManipulateGameObject); }
//callback function void ManipulateGameObject(GameObject go) { go.GetComponent<Collider>.isTrigger = true; }
//wrapper for the coroutine, stops you needing to add on StartCoroutine void GetObjectViaWWW(string url, Action<GameObject> callback) { StartCoroutine(GetObjectViaWWWCoroutine(url, callback)); }
//Action<T> is a delegate which takes one parameter, void return type IEnumerator GetObjectViaWWWCoroutine (string url, Action<GameObject> callback) { //make a game object, various setup yield return StartCoroutine(WaitForResponse(www)); //do stuff with gameobject callback(createdGameobject); }
public IEnumerator WaitForResponse(WWW www) { yield return www; // check for errors if (www.error == null) etc. }
Your answer
Follow this Question
Related Questions
Nested Coroutines Waiting for Each Other 1 Answer
How to save to a database on application close 2 Answers
Ios problem with www class 2 Answers
How to yiled a try/catch block? 2 Answers