- Home /
Instantiate + Coroutine = problem
How could I instantiate (i.e. create a copy with the exact same state) game objects that starts coroutines, since Unity Instantiate won't save the coroutine state? Example:
public class CoroutineTest : MonoBehaviour {
public IEnumerator DoIt()
{
Debug.Log("First print");
yield return new WaitForSeconds(15.0f);
Debug.Log("Last print");
}
void Start()
{
StartCoroutine(DoIt());
}
[ContextMenu("Clone")]
private void Clone()
{
var obj2 = (CoroutineTest)Instantiate(this);
}
}
If I hit Play and after some 5 secs Clone, I'll have this answer:
First print
First print
Last print
Last print
While in the perfect world I would have:
First print
Last print
Last print
I'm looking for solutions that won't make me implement a state machine inside the coroutine.
Interesting. It's arguably a bug, but not likely to change any time soon, because by the same argument, Start should not be called on clones that have already started, there children should keep their active states, etc.
Sorry, but I think your going to have to be able to recover the Coroutine state yourself from instance variables, which means a state machine in the coroutine.
"Start is only called once in the lifetime of the behaviour". A clone of a script (including the GameObject) is a completely new instance and therefore another $$anonymous$$onoBehaviour. When it is created, Awake is called (from the internal constructor) and next frame, Start is called.
Instantiate will not make a deep memory copy (which wouldn't help btw.). It's just serializing the object (public fields and all fields marked with SerializeField) and deserialize the values on the new created object.
Coroutines are actually statemachines. Every coroutine will produce a seperate internal nested class that represents the coroutine. The class just implements the IEnumerater interface and all the code you've writting in your coroutine will go into the $$anonymous$$oveNext() function which has some kind of a switch-case construct in it. All that is hidden from you and Unity. That's completely handled by the C# / $$anonymous$$ono compiler.
Here are some great articles about coroutines in C#:
A custom coroutine scheduler:
http://www.unifycommunity.com/wiki/index.php?title=CoroutineScheduler
A great example what happens behind the scenes when you use "yield"
http://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/
@Bunny83 this is also a very well written and comprehensive article about coroutines http://altdevblogaday.com/2011/07/07/unity3d-coroutines-in-detail/
Yeah, really nice a bit more about the scheduling stuff. We can only guess how Unity implemented their scheduler but i think it's quite similar.
Read the comments, Lucas $$anonymous$$eijer from UT tells him is absolutely spot-on! And he says some other stuff.. then I had to tell him he was wrong. :p