Function not waiting

I’m trying to get this enemy function to wait for the death animation to play before destroying the game object, otherwise it gets destroyed before the animation finishes. I’ve looked online and it seems that I’m doing everything right, but it just won’t wait.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    [SerializeField] float health, maxHealth = 3f; // This creates two variables, health and max health. SerializeField is needed so that these variables can stay private but be accessible within the Unity editor

    public Animator anim;

    private void Start()
    {
        health = maxHealth;
    }

    private IEnumerator Wait()
    {
        yield return new WaitForSeconds(5);
    }

    public void TakeDamage(float damageAmount) // Method that takes in a damage amount as a float and inflicts it upon the enemy
    {
        health -= damageAmount; // The damage amount is taken away from the current health

        if (health <= 0) // If the enemy has not more health left once it has taken damage:
        {
            anim.SetTrigger("Death");
            StartCoroutine (Wait());
            Debug.Log("Waiting");
            Destroy(gameObject); // Then it dies
        }
    }

}

thats not how it works, you have to do something like this

 private IEnumerator WaitAndDie()
    {
        yield return new WaitForSeconds(5);
 Destroy(gameObject); // Then it dies
    }

StartCoroutine (WaitAndDie());
1 Like

Please don’t use the 2D tag unless you’re asking about 2D features. This should be tagged “Scripting”.

I’ll do that for you.

Thanks.

1 Like

This worked, thank you!
I’m sure this was a big beginner mistake, but I just simply didn’t have the time to do in depth research about coroutines.

I would recommend against using things you don’t have the time to understand. :slight_smile:

Coroutines in a nutshell:

Splitting up larger tasks in coroutines:

Coroutines are NOT always an appropriate solution: know when to use them!

“Why not simply stop having so many coroutines ffs.” - orionsyndrome on Unity3D forums

Our very own Bunny83 has also provided a Coroutine Crash Course:

And another overview by Anders Malmgren:

2 Likes

Thank you so much for the explanation!
The reason that I’m not doing research into coroutines is because this is a school project where I predict that I will only use this feature once, and I only have a few days to finish basically the entire thing cos I’m an idiot :slight_smile:
But I will definitely look over this again to make sure I understand it fully once I have the time, so I appreciate this a bunch!