## A Better Way To Use The Animator

Posted by Jordan on April 29, 2017

Hi all,

As you can see above, my animator in Unity3D is a complete mess that isn't worthy of much love! It looks like some spider lives there and it caught a bunch of shitty parameters. Well I've finally cleaned it up and made it a million times more efficient and easier to read! Instead of using triggers and booleans, I use a single integer parameter called State. Each integer value for State correspondes to a certain animation (Idle, Run, Jump, etc). This can be seen in the image below. This means transition to Idle when State is 0, transition to Run when State is 1, and etc. So remember, a unique integer number for State is associtated with an animation state! Notice that everything is attached to 'Any State', meaning you can transition to any of these states from ANY current state! Instead of having a boolean or trigger parameter, we only have this simple single integer parameter State.

Wow, look how much better that looks than before! Ok now we move on to the script that controls the animator. First I made an Enum variable that has the same states in my animator, but order is very important here! In my animator I have the parameter State transition to Idle when State is 0, transition to Run when State is 1, and etc. Hence, my enum order should be the same as my animator (public enum State {Idle, Run, ... };). Therefore, if I cast my enum to an interger when it is equal to Idle, then it will return the value 0. That means, 0 should be the integer value for the animator parameter State to transition to the Idle animation. Here is a quick example of how this would work.

public Animator animator;

publc enum State {Idle, Run, Attack};
public State currentState;

public bool isAttacking = false;
public bool isRunning = false;

void Update()
{
if(isAttacking)
{
currentState = State.Attack;
}
else if(isRunning)
{
currentState = State.Run;
}
else
{
currentState = State.Idle;
}

animator.SetInteger("State", (int)currentState);
}


So if instead we only had three different states => Idle, Run, or Attack. Then our animator controller would have the parameter State transition to Idle when it was 0, transition to Run when it was 1, and transition to Attack when it was 2. Then we determine what state we are in based on the booleans isAttacking, or isRunning. If you aren't attacking or running, then the state will default to Idle. But as soon as isAttacking is true, then you will transition to the attack animation. Also notice that the booleans are in an if else statement, meaning if isAttacking and isRunning are both true, then your current state will transition to attack instead of run.

I hope this helps, good luck!