- Home /
My Coroutine does not get called
Currently have this code: void Update () {
if (playerHealth <=0 && !isDead)
{
levelManager.player.DeathAnimation();
playerHealth = 0;
levelManager.RespawnPlayer();
lifeSystem.TakeLife();
isDead = true;
thetime.ResetTime();
}
Above is my Health script, when the player dies it calls the deathAnimation() function off Player
public void DeathAnimation()
{
Debug.Log("1");
StartCoroutine("DeathAnimationCo");
Debug.Log("2");
}
public IEnumerable DeathAnimationCo()
{
Debug.Log("3");
anim.SetBool("isDead", true);
Debug.Log("4");
yield return new WaitForSecondsRealtime(2f);
}
In the block of code above you see I start my coroutine, in my coroutine I start running my animation and then try to do a yield return to wait for 2 seconds ( so my animation can finish) .
Currently the debug log "3" and "4" do not get called. The animation doesn't start playing at all ( but the code in my Health script does get called, so the player object gets destroyed and reset (as intended)).
Anybody an idea of what I'm doing wrong?
Answer by DJJD · Oct 11, 2017 at 09:37 PM
As Birdman said, you need to switch the IEnumerable for IEnumarator. In top of that, you should probably, as a good practice, stop writing your coroutines in a string form.
Try StartCoroutine(DeathAnimationCo()); instead. You'll be sure the coroutine will be called this way, else you will get an error (which you would not if you use a string).
Cheers!
Right, Unity doesn't recognise a method that return an IEnumerable as coroutine, though it would still work when used correctly. The IEnumerable interface is just one step above the IEnumerator.
This would work even with IEnumerable as return type:
StartCoroutine(DeathAnimationCo().GetEnumerator());
Though normally a coroutine should have IEnumerator as return type so you can simply do
StartCoroutine(DeathAnimationCo());
Answer by Birdman1011395 · Oct 11, 2017 at 09:30 PM
IEnumerator is the return type for coroutines, not IEnumerable.
Answer by TBART82 · Oct 12, 2017 at 01:01 AM
Change:
StartCoroutine("DeathAnimationCo");
To:
StartCoroutine(DeathAnimationCo());
And
public IEnumerable DeathAnimationCo()
{
Debug.Log("3");
anim.SetBool("isDead", true);
Debug.Log("4");
yield return new WaitForSecondsRealtime(2f);
}
To
public IEnumerator DeathAnimationCo()
{
Debug.Log("3");
anim.SetBool("isDead", true);
Debug.Log("4");
yield return new WaitForSecondsRealtime(2f);
}
Answer by Skibur · Oct 12, 2017 at 02:46 AM
Alternative solution, instead of using coroutine, why not use Invoke() instead?
public void DeathAnimation()
{
Debug.Log('3');
anim.SetBool("isDead", true);
Debug.Log('4');
Invoke("DelayMethodHere", 2f);
}
public void DelayMethodHere()
{
//code executes after nth seconds from Invoked.
}
While changing it to IEnumerator fixxed it, this worked even better for what I was trying to do. Thanks :)