- Home /
Why is yield not working for me?
Here's my code:
function OnTriggerEnter(collider:Collider){
var gameController = gameObject.Find("GameController").GetComponent(GameController);
if(collider.gameObject.tag.Equals("Enemy"))
{
gameController.lives--;
}
if(gameController.lives == 0)
{
Instantiate(playerExplosion, transform.position, Quaternion.identity);
Destroy(this.gameObject);
yield WaitForSeconds(2);
gameController.gameOver = true;
}
}
heres how it goes, im trying to make a game over button. when gameController.gameOver = true, a gui button will appear in the screen, but the problem is, without the yield, it goes off instantly and it doesnt give the explosions to show themselves, so what i did was put a yield. when i put the yield on the code, the button doesn't show up in the screen. what seems to be the problem? could someone please explain it to me? :D
Heres the code for the game over button:
if(gameOver == true)
{
pauseGame();
showPauseButton = false;
if (GUI.Button (Rect((Screen.width *.50) - 65, (Screen.height * .50) - 22.5, 130,45), "Try Again")) {
Application.LoadLevel(Application.loadedLevel);
gameOver = false;
showPauseButton = true;
unpauseGame();
}
}
Answer by Eric5h5 · Aug 05, 2012 at 05:07 PM
You've destroyed the object, so it can't yield for 2 seconds since it doesn't exist anymore. Either don't destroy the object right away or call a coroutine on an object that doesn't get destroyed. You could teleport the object far away so it's out of the way:
Destroy (gameObject, 2);
transform.Translate (Vector3.right * 10000);
yield WaitForSeconds(2);
gameController.gameOver = true;
It's probably best just to make a coroutine on the GameController and call that, though:
Destroy (gameObject);
gameController.GameOverRoutine();
Where GameOverRoutine is this:
function GameOverRoutine () {
yield WaitForSeconds(2);
gameOver = true;
}
In a totally platonic way, I assume. ;) If this answer helped you, then you can click on the checkmark to accept it.
Answer by Dragonlance · Aug 05, 2012 at 10:15 AM
Hi Roncel,
you can not use yield WaitForSeconds in a Callback function. It only works in a Coroutine
WaitForSeconds can only be used with a yield statement in coroutines.
http://docs.unity3d.com/Documentation/ScriptReference/WaitForSeconds.html
So you should start a coroutine there and make the Trigger unfunctional with if(!gameOver){}
"OnTriggerEnter can be a co-routine, simply use the yield statement in the function." -- The Docs
Your answer
Follow this Question
Related Questions
How to make this function disable after 5seconds 1 Answer
[Android] Why does my enemy die no matter where I am in the 3D environment? 1 Answer
Level Button And Quit Button Android 2 Answers
GUI Texture Resolution 0 Answers
Scrolling Text 1 Answer