- Home /
Inserting a delay
var lowerBody:GameObject;
function Update (){
if (Health.health==0){
//Where the delay should be
Health.health=100;
transform.position=Vector3(0,8,0);
lowerBody.transform.position =Vector3(0,0.5,0);
}
}
How can I delay the function 5 seconds at this point? I understand that I should likely be using while(){ and yield WaitForSeconds, but I can't figure out exactly how the syntax should work.
Answer by fafase · Apr 05, 2012 at 08:49 AM
Remember you need to put it in a coroutine that you call in the update.
This below is bad and won't work as the update needs to freely run.
var lowerBody:GameObject;
function Update (){
if (Health.health==0){
yield WaitForSeconds(5); // here this is wruuuung
Health.health=100;
transform.position=Vector3(0,8,0);
lowerBody.transform.position =Vector3(0,0.5,0);
}
}
Proper way:
var lowerBody:GameObject;
function Update (){
if (Health.health==0){
WaitHere(); // you call
}
}
function WaitHere(){
Health.health=100;
yield WaitForSeconds(5); // the function waits 5 sec before doing what is next
// in the meanwhile everything else keeps going.
transform.position=Vector3(0,8,0);
lowerBody.transform.position =Vector3(0,0.5,0);
}
wouldn't that script call the waithere() function for multiple times for 5 seconds? once per update?
maybe you should use a "respawning" or such variable, which turns to true when the health drops to 0, and in the Update() if statement you make a check if it's false so it wouldn't call the WaitHere() multiple times. Then in the WaitHere() function you should set it back to false after setting the Health back to 100.
I edited the answer (it should come up later on), actually yes you can do all that or simply put the health=100 before the yield so that the if statement is false. Now if he wants the health to wait before changing back to 100, he can do the same process.
And maybe a fadeout-fadein would be a good idea until the repositioning and health changing is done.
The question is about waiting, fade in-fade out is a material issue that was not asked by the user.