Search Unity

Can't get animation working in script

Discussion in 'Scripting' started by oscaro, Apr 18, 2015.

  1. oscaro

    oscaro

    Joined:
    Apr 7, 2015
    Posts:
    18
    Not sure if the problem is in the script or the animator, but I can't get an object to animate. I've done it plenty of times before but this time it doesn't seem to be working even though I'm using the same method as all the other times I've done it. I basically want an enemy to animate being hurt every time it is hit by the player.

    The enemy does have a Animator component, I have set the isBeingHit bool in the Animator, the script is on the enemy, and I have made transitions with all the animations.

    My code:
    Code (csharp):
    1.  
    2. Animator anim;
    3.  
    4.     void Awake() {
    5.         // Initialising
    6.         isAlive = true;
    7.         beingHit = false;
    8.         // References
    9.         anim = GetComponent<Animator>();
    10.     }
    11.  
    12.     void Update() {
    13.         // If the enemy is alive
    14.         if (isAlive) {
    15.             // If the enemy is being hit
    16.             if (beingHit) {
    17.                 // Animate being hurt
    18.                 anim.SetBool("isBeingHit", true);
    19.                 // Take away from the enemies health
    20.                 enemyHealth -= 1;
    21.                 // Stop animating
    22.                 anim.SetBool("isBeingHit", false);
    23.                 // Stop being hit until the player hits again
    24.                 beingHit = false;
    25.             }
    26.      
    27.             // If the enemy runs out of health
    28.             if (enemyHealth <= 0) {
    29.                 // It is not alive
    30.                 isAlive = false;
    31.             }
    32.             // If the enemy is not alive
    33.             if (isAlive == false) {
    34.                 // Destroy it
    35.                 Destroy(gameObject);
    36.             }
    37.         }
    38.     }
    39.  
    Any and all help is greatly appreciated. Thanks.