- Home /
Another question about yield, WaitForSeconds in c#
Hi
I was reading toons of posts regarding WaitForSeconds in c# and cant get it working. "WaitForSeconds" just don`t run like not beeing in code.
Any clues ????
using UnityEngine;
using System.Collections;
using System;
public class MyCreator : MonoBehaviour {
public GameObject box;
public bool readynow = true;
int counter =0;
public int limit=100;
// Update is called once per frame
void Update () {
if(counter<=limit) {
StartCoroutine(MakeBox());
counter++;
}
}
IEnumerator MakeBox() {
readynow=false;
Instantiate(box, transform.position, transform.rotation);
yield return new WaitForSeconds(4.0f);
readynow=true;
}
}
For one thing, you're starting a new instance of the coroutine every frame for the first 101 frames.
Answer by syclamoth · Feb 26, 2012 at 03:37 AM
What do you expect this code to do? Right now, I would expect it to run like this:
once per frame, start the box coroutine, until the counter reaches 101.
In this box coroutine, it spawns a box immediately and switches a boolean (that isn't used anywhere else in the code).
4 seconds later, the boolean gets switched back. Again, since this bool isn't used anywhere else in the code, I would expect it to do nothing. You may as well just remove the coroutine entirely, since the way you are using it now is identical to simply instantiating a box once per frame (except with a little more overhead).
If, as I suspect, you actually want it to instantiate a box every 4 seconds, you should instead structure it a bit more like this:
IEnumerator MakeBoxes(int boxCount, float boxDelay) {
for(int i = 0; i < boxCount; ++i)
{
Instantiate(box, transform.position, transform.rotation);
yield return new WaitForSeconds(boxDelay);
}
}
Then, use StartCoroutine once from Start, and let the coroutine manage the timing.
Otherwise, what will happen is the 101 boxes will spawn, then 4 seconds after the first one appears, the boolean will reset. After this, it will be impossible to change the boolean permanently for about 101 frames, and then the coroutines will have finished.
Answer by letmeknowit · Feb 26, 2012 at 04:10 PM
Well syclamoth u make me think about this issue more and i found solution to this problem. The code u showed me is nice and simple and i like it.
My question/issue was made by trying make this tutorial lesson tutorial lesson -pausing scripts- parsed as c# script. But to the point, i found information that Coroutines can`t be started from update() function .. thats why this wasn`t working. Thanks for pointing me in solution direction.
regards letmeknowit
Your answer
Follow this Question
Related Questions
C# WaitForSeconds doesn't seem to work ?? 2 Answers
Yield and WaitForSeconds not stopping at correct points? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers