- Home /
coroutine help
Hello, so I got a coroutine with a WaitForSeconds() statement, but I want the coroutine to have 2 ways to continue for the player, to wait for x seconds before the next enemy spawns or hurry the time for the next spawn with a button press. Any idea on how this can be done? I just need a general idea, I am not asking for any code, thank you all in advance!!!
Answer by Jeff-Kesselman · May 07, 2014 at 01:27 AM
Yes.
Write the code that goes on as a separate routine that is called either from your co-routine's continuation or directly by a user press. Have it set a boolean that says its been called so, if the user calls it, and then the co-routine completes, it will just ignore the second call.
Answer by robertbu · May 07, 2014 at 01:28 AM
I know you did not want any code, but sometimes an example is faster and better than a long description. There are a number of different approaches. Here is one. Put this on an empty game object and run. Space will speed the current cycle.
#pragma strict
var abort = false;
function Start() {
DoTheAction(5.0);
}
function DoTheAction(time : float) {
while (true) {
var timer = 0.0;
while (timer < time && !abort) {
Debug.Log(timer);
timer += Time.deltaTime;
yield;
}
Debug.Log("#######Instantiate#######");
abort = false;
// Instantiate code goes here;
}
}
function Update() {
abort = Input.GetKeyDown(KeyCode.Space);
}
Note that by using just 'yield' and a timer, instead of 'yield WaitForSeconds()', we can check to see if the user hit a key each frame.