Yield wait for seconds not working at all?
Everything else about this works, and I have the identical script on another gameObject and it works, but right here it will not. The player respawns to the proper spawnpoint when killed, but the KillPlayer function will not run as the respawn happens instantly...:
public IEnumerator KillPlayer () {
Debug.Log ("got to coroutine");
yield return new WaitForSeconds (5f);
}
if (target.gameObject.tag == "deadly") {
StartCoroutine("KillPlayer");
transform.position = new Vector2 (spawnpoint.position.x, spawnpoint.position.y);
AudioSource.PlayClipAtPoint (deathsound, transform.position);
PLives -= 1;
PHealth = 10;
}
}
I know it seems simple but I can't figure it out! Thanks..
Answer by Socapex · Dec 31, 2015 at 08:47 PM
If I understand correctly, you want to wait 5 seconds, then move the player? You have to put the position line inside the coroutine, after the yield.
If my guess is correct, and you want more explanation on Coroutines, I'd be happy to talk about them. They are an essential tool of your programming arsenal.
Answer by Raistlin2015 · Jun 15, 2016 at 12:20 AM
All of the code you want to execute after the time set in the WaitForSeconds()
has to be written below the yield return new WaitForSeconds()
Also your sintax was incorrect on the StartCoroutine()
call. Sorry for the late answer but hopefully this will help whomever may have this problem in the future.
public IEnumerator KillPlayer ()
{
Debug.Log ("got to coroutine");
yield return new WaitForSeconds (5f);
transform.position = new Vector2 (spawnpoint.position.x, spawnpoint.position.y);
AudioSource.PlayClipAtPoint (deathsound, transform.position);
PLives -= 1;
PHealth = 10;
}
public void FunctionToKillPlayer()
{
if (target.gameObject.tag == "deadly")
{
StartCoroutine(KillPlayer());
}
}
Your answer
Follow this Question
Related Questions
Yield WaitForSeconds doesn't work! 1 Answer
Add an value to a variable after 2 seconds 1 Answer
Trouble with Co routines & WaitForSeconds 0 Answers
Trying to make dash energy system... 1 Answer
yield ends method 0 Answers