yield WaitForseconds not working?
HI,
my code below doesn't seem to wait for 5 seconds before executing the code
var gameState : String;
var circleColor : int;
function Start () {
Debug.Log("The game has started");
gameState = "play";
}
function Update () {
WaitFor_Seconds(5);
ChangeCircleColor();
}
function ChangeCircleColor () {
if(gameState == "play") {
circleColor = Random.Range(1,5);
if(circleColor >= 2) {
gameObject.GetComponent.<Renderer>().material.color = Color.green;
}
else {
gameObject.GetComponent.<Renderer>().material.color = Color.red;
}
}
}
function WaitFor_Seconds(time) {
yield WaitForSeconds (time);
}
Tnx Adam
Some quick researching and you'll find out everything you need to know about coroutines. In this case when your WaitFor_Seconds() coroutine executes it waits for 5 seconds and then does nothing, and this execution is happening every frame which I'm willing to bet will lead to some undesired behavior.
Here are some useful links that will help you understand and properly use coroutines: Link 1, Link 2, Link 3.
Answer by Denvery · Sep 22, 2015 at 06:26 PM
Hello, Adam!
You cannot use WaitForSeconds
in Update
, because Update is called every frame. Please write something like this:
function Start ()
{
Debug.Log("The game has started");
gameState = "play";
WaitFor_Seconds(5);
ChangeCircleColor();
}
P.S. Almost similar Q: http://answers.unity3d.com/questions/375656/execute-coroutine-in-update.html
Your answer
Follow this Question
Related Questions
Javascript Script for Object Follow? 0 Answers
Function Update not working 1 Answer
how to switch between 2 values after 5 seconds using waitforseconds 2 Answers
Animation Types Won't Play 0 Answers