In my update function, I have an if function to determine if my object is near to the ground., if it is it changes the animation and loads the walkOrIdle function, I only want this to be called every five seconds but im having problems, it runs the code after 5 seconds and then all the time, not at intervals, any ideas how to execute the code?
function Update() {
if (transform.position.y >1){//if at ground.
//randomise between idle and walking
animation["fly"].wrapMode = WrapMode.Once;
animation.Blend("walk", 0.5, 0.2);
walkOrIdle();
}
function walkOrIdle()
{
yield WaitForSeconds (5);
//do something
}
Your code in Update() gets called each frame and starts countless coroutines, each waiting for five seconds and then executing, so the code in walkOrIdle will be called each frame after those five seconds.
You maybe want to do something like this:
var onGround = false;
function Start() {
if (!onGround transform.position.y > 1) {
onGround = true;
StartCoroutine("walkOrIdle");
} else if (onGround transform.position.y <= 1) {
onGround = false;
StopCoroutine("walkOrIdle);
}
}
function walkOrIdle() {
while (true) {
yield WaitForSeconds(5);
// Do stuff
}
}
Which will execute the code all five seconds while grounded.
ok, but I need to check if my gameobject is <1 every frame as its moving to random positions thoughout the level, and with your code, it only checks on start, how can I do this?