- Home /
Unsure of how to make a certain animation play
I am relatively new to scripting and I am in the process of learning C#. This site has been helping me a lot with previously answered questions but unfortunately I can't find an answer to this particular question which I am asking.
I want to know how to make a certain animation play with Unity's animator component. I have gotten running, jumping, and other animations to work fine. However, I am unsure how to play a "gettingHit" animation the right way. By that I mean, I want an animation to play when my player gets hit by an enemy attack.
I'm not sure whether this is a small problem like I have just been misplacing my code, or if I need to change some lines to get it to work. Below are the lines I have been trying to place into the script in various places and changing things around trying to get it to work properly but I can't seem to figure it out.
if (gettingHit) {
gettingHit = false;
animator.SetBool ("GettingHit", false);
}
if (*****notsurewhatgoeshere*****) {
gettingHit = true;
animator.SetBool ("GettingHit", true);
}
Here is what the rest of the script looks like: `using UnityEngine; using System.Collections;
public class PlayerHealth : MonoBehaviour { public float maxHealth = 100; public float curHealth = 100; public float healthbarlength; private bool dead; private Animator animator; private bool gettingHit;
void Start () {
animator = GetComponent<Animator>();
healthbarlength = 250;
}
void Update () {
if (dead) {
dead = false;
animator.SetBool ("Dead", false);
}
if (curHealth <= 0) {
dead = true;
animator.SetBool ("Dead", true);
}
}
void OnGUI(){
GUI.Box(new Rect(10, 10, healthbarlength, 20), curHealth + "/" + maxHealth);
}
public void ApplyDamage ( float damage ){
if (curHealth > 0){ // if enemy still alive (don't kick a dead dog!)
curHealth -= damage; // apply the damage...
}
// <- enemy can emit some sound here with audio.Play();
if (curHealth > maxHealth) {
curHealth = maxHealth;
if (curHealth < 0){ // if health has gone...
curHealth = 0;
// enemy dead: destroy it, explode it etc.
}
}
healthbarlength = 250 * (curHealth / (float)maxHealth);
}
}`
Thanks for taking the time to view the problem I have been having. Oh and don't mind the "dead" animation that is just what I will be working on after I get the hit animation working properly.
Answer by superluigi · Jan 26, 2014 at 12:09 AM
I would have something like
function OnTriggerStay(other : Collider)
{
if(!invincible)
{
if(other.gameObject.tag == "Enemy")
{
gettingHit = true;
animator.SetBool ("GettingHit", true);
invincible = true;
yield WaitForSeconds(1);
invincible = false;
animator.SetBool ("GettingHit", false);
}
}
}