i don't know why my butterfly use his wing-animation every Update, without waiting random seconds.
he was supposed to wait for random seconds in every Update.
here is my try :
function Update(){
WaitSeconds(); //wait random seconds for animation
}
function WaitSeconds () {
var randomWait = Random.Range(0, 6);
print ("warte" + randomWait + " Sekunden"); //debug
yield WaitForSeconds(randomWait);
animation.Play("Default Take");
}
2 Answers
2
Update() is called every frame. You are creating a new animation coroutine everyframe. change Update() to Start() or add a bool in your update that makes sure WaitSeconds() is only called once like this:
var playAnim : boolean = true;
function Update(){
if (playAnim)
WaitSeconds(); //wait random seconds for animation
}
function WaitSeconds () {
playAnim = false;
var randomWait = Random.Range(0, 6);
print ("warte" + randomWait + " Sekunden"); //debug
yield WaitForSeconds(randomWait);
animation.Play("Default Take");
// detect when anim is complete
// playAnim = true;
}
You can get better performance using an infinite loop. Calling Update every frame like that is just a waste of processing power. Instead you should do something like.
function Start(){
WaitSeconds(); //wait random seconds for animation
}
function WaitSeconds () {
while(true) {
var randomWait = Random.Range(0, 6);
print ("warte" + randomWait + " Sekunden"); //debug
yield WaitForSeconds(randomWait);
animation.Play("Default Take");
}
}
This will give you much better performance than your current method because the processor only has to do work every randomWait seconds. Calling Update like you were is called via Reflection internally and isn't that fast comparatively.
Think about it this way. If the wait is 5 seconds and you get 30 FPS, then you will waste 150 Update() calls waiting to call your coroutine again. This eliminates that.
great, exactly what i need, thank you very much ! by the way : bool -> boolean
– cacysunleefixed bool to say boolean in the answer!
– loopyllama