Search code examples
c#unity-game-engineunity3d-2dtools

Unity 2D - How to play death animation prefab


I have created a prefab with animation from sprite sheet, which I want to be played when the Player dies. I checked if the prefab is working by dragging it in the Scene, and it is correctly playing every frame of the sprite sheet in a loop endlessly.

Now I want to play this prefab when the Player dies, and after it ends to destroy it, but so far I am only able to place it where the player dies, and it stays there forever. Also there are some errors when that happens.

Here is the death script:

 public class DmgByCollisionEnemy : MonoBehaviour {

    public GameObject deathAnimation;

    void Die() {
        deathAnimation = (GameObject) Instantiate(deathAnimation, transform.position, transform.rotation);
        //Destroy(deathAnimation);
        Destroy(gameObject);
    }
}

I set the deathAnimation by dragging a prefab in the Unity interface.

The error I am getting when the Die() method fires is

UnassignedReferenceException: The variable deathAnimation of DmgByCollisionEnemy has not been assigned.
You probably need to assign the deathAnimation variable of the DmgByCollisionEnemy script in the inspector.

So how can I do that properly?


Solution

  • You can try to add simple destroy script to Your death animation object that destroys object after time or trigger it in animation (Unity Manual: Using Animation Events). When you instantiate object it will appear on desired position and it will be destroied regardless to "main" object.

    Destroy Script like this:

    void DestroyMyObject() 
    { 
       Destroy(gameObject); 
    }
    

    Script to run after time:

    void Start() 
    {
        Invoke ("DestroyMyObject", 1f);
    }
    
    void DestroyMyObject()
    {
        Destroy(gameObject);
    }
    

    Spawn script:

    using UnityEngine;
    using System.Collections;
    
       public class SpawnExtra : MonoBehaviour {
    
       public GameObject deathAnimation;
    
       public static SpawnExtra instance;
    
       void Start () 
       {
            instance = this;
       }
    
       public void SpawnDeathAnimation(Vector3 position)
       {
            Instantiate (deathAnimation, position, Quaternion.identity);
       }
    }
    

    And you can use it when you want to spawn additional object like this:

    SpawnExtra.instance.SpawnDeathAnimation (transform.position);
    

    Now you have to add gameobject e.g ExtrasController, add script on it and you can spawn whatever you want. Remember to drag&drop animation prefab in inspector.