Playing a longer running animation in Unity

January 01, 2016

Continuing on with my list of things that I’ve found in unity (I’m using 5, but have no reason to believe these wouldn’t work for 4), I had cause to execute an attack animation in a character. For reference, the character I’ve been using is here

So far, when playing an animation, I’ve used something similar to this:



gameObject.GetComponent<Animation>().Play("Idle\_2");

In fact, if you put that in the Update of the linked object, you’ll get an angry looking chap looking like he’s about to charge. In order to plumb in the attack, it’s necessary to cache the animation. Start with a class level variable:



private Animation \_animation;

Then, inside the update statement, something similar to this:



void Update ()
{
    if (\_animation != null && \_animation.IsPlaying("Attack\_1")) return;

    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (\_animation == null)
            \_animation = gameObject.GetComponent<Animation>();
        \_animation.Play("Attack\_1");            
    }
}


One of the bizarre things that I learnt about unity while doing this, was that if you have a null reference, it doesn’t crash. It doesn’t work, but it doesn’t crash.

I find this annoying.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024