Search Unity

Question How to make player death animation play

Discussion in '2D' started by unity_xR0hRAiY0ja-MA, Aug 31, 2020.

  1. unity_xR0hRAiY0ja-MA

    unity_xR0hRAiY0ja-MA

    Joined:
    Jul 30, 2020
    Posts:
    1
    Hi everyone,
    I'm new to Unity and I've been working on a prototype of a slash em up game. I feel fairly comfortable with creating animations and using the animator controller to apply them to game objects. I've managed to create a system for the transitions between being hurt and dying for the enemies and it works as expected. However, when I tried to replicate the system for the player, only the hurt animations works/plays when expected. When the player dies, the Die() function is called but the animation does not play and I am unable to figure out why. In the picture below you can see the transition states.


    In the log, I can see that the player is taking damage, and the hurt animation plays. When the player's health reaches 0, then the player movement is disabled and the log says "Player died!" but the animation does not play. I thought maybe it was because I disabling the player, but leaving the player enabled did not change anything. It just meant that I could continue moving and attack as the player.

    The code for the enemy hurting the player and the player taking damage and dying is below.

    Code (CSharp):
    1. //Enemy script
    2.  
    3. void OnCollisionEnter2D(Collision2D col)
    4.     {
    5.         if (col.gameObject.tag.Equals("Player"))
    6.         {
    7.             doDamage();
    8.         }
    9.     }
    10.  
    11.     void doDamage()
    12.     {
    13.         target.GetComponent<PlayerMovement>().takeDamage(goblinDamage);
    14.     }
    Code (CSharp):
    1. //PlayerMovement script
    2.  
    3. public void takeDamage(int goblinDamage)
    4.     {
    5.         currentHealth -= goblinDamage;
    6.         Debug.Log(currentHealth);
    7.      
    8.  
    9.         //hurt anim
    10.         animator.SetTrigger("Hurt");
    11.  
    12.         if (currentHealth <= 0)
    13.         {
    14.             Die();
    15.         }
    16.     }
    17.  
    18.     void Die()
    19.     {
    20.         Debug.Log("Player died!");
    21.  
    22.         //Die anim
    23.         animator.SetBool("IsDead", true);
    24.  
    25.         //Disable the player
    26.         GetComponent<Collider2D>().enabled = false;
    27.         this.enabled = false;
    28.  
    29.         //Delete after 3 seconds
    30.         //Destroy(gameObject, 3f);
    31.  
    32.  
    33.     }
    any help would be greatly appreciated, thank you!