- Home /
WaitForSeconds, only pausing once
I have a WaitForSeconds (which I use to rotate something for a fix amount of time, then reverse the rotation) but it happens once, then it keeps calling rotateSpeed *= -1; and skips the yield return new WaitForSeconds(waitFor);
void Update()
{
RotateCamera();
}
private void RotateCamera()
{
transform.Rotate(Vector3.forward * Time.deltaTime * rotateSpeed);
StartCoroutine(Timer());
}
private IEnumerator Timer()
{
yield return new WaitForSeconds(waitFor);
rotateSpeed *= -1;
}
Answer by gfr · Nov 03, 2011 at 01:30 AM
As written you start a new coroutine every frame, leading to rotateSpeed *= -1;
being executed roughly every frame after waitFor
has passed.
If you want the coroutine to run only once, set a flag to remember that it is already running.
@gfr thanks! I don't want it to run only once, but I want it to be paused for a set amount of time (int waitFor). I want it to rotate one way for 3 seconds, and then to hit the rotateSpeed *= -1 then to rotate the other way for 3 seconds... and continue this forever!
oh i see what you are saying though. I am creating so many Timer coroutines, that once the 3 seconds is done, the other coroutines 3 seconds are finished as well.
You only need one - that's where loops come in, e.g. something like:
while (true) {
// yield ...
// do stuff
// some exit condition ...?
}
excellent! thanks! should've figured that the routine was getting called a million times, thought it was called only after the waitforseconds was done.
An alternative would be to call it in the Awake() function. That way you won't have the overhead of another variable.
Your answer
Follow this Question
Related Questions
JS WaitForSeconds Not Working? 1 Answer
Make delay for spawn 3 Answers
Waiting for fractions of a Second 1 Answer
Coroutine confusion 1 Answer
How do i add a delay to how often a unity ui button may be used? 1 Answer