- Home /
IEnumerator problems in C#
So my problem is that my IEnumerator function won't start. Here is the code I use:
void Update(){
Do();
}
IEnumerator Do () {
Debug.Log("HERE");
yield return new WaitForSeconds(5.0F);
Instantiate(AIBullet, transform.position, transform.rotation);
}
I'm not getting the Debug message and nothing is happening.
Answer by Peter G · Aug 01, 2011 at 12:02 AM
In C#, you have to use StartCoroutine()
void Update () {
StartCoroutine( Do() );
//or the less efficient version that takes a string, but is limited to a single parameter.:
StartCoroutine("Do" , parameter);
//The advantage to the string version is that you can call stop coroutine:
/StopCoroutine("Do");
}
Using the version that takes a string, I'm getting the IEnumerator function to repeat over and over again, but only the message is repeating. So I'm being flooded with the debug message but only once does it wait for 5 seconds then instantiate the object. It seems like it only listens to the last two lines one time.
That's because your calling it from Update(). As Statement is saying, Update will be called every frame even if you start a coroutine. So here's what you time sequence looks like:
Frame 0: Start Coroutine.
Frame 1: Start SameCoroutine.
Frame 2: Start Same Coroutine.
//....
5 Seconds + 0 frames: Fire Bullet:
5 Seconds + 1 Frame: Fire Bullet:
So after that 5 second delay, you will fire every second. In your case it might be easier to use InvokeRepeating:
void Start () {
InvokeRepeating( "Do" , 5 , 5 );
}
or an infinite loop:
IEnumerator Start () {
for(;;) {
Do();
yield return new WaitForSeconds(5.0f);
}
}
Answer by Statement · Aug 01, 2011 at 02:09 AM
Coroutines won't "hold up" Update. Check out CoUpdate pattern to use logic-blocking calls.
Your answer
Follow this Question
Related Questions
Return statement in IEnumerator Unity C# 1 Answer
ISerialization madness 2 Answers
Is Input.GetAxis meant to return to 0 on key up? 1 Answer
Calling IEnumerator function with variables does not do anything 1 Answer
Freeze frame for iTween? 0 Answers