Skip to main content

Using blendtrees for animations on 2D sprites in Unity

· 3 min read
Brock Davis

Recently I was working on creation an animation for a game I am working on on the side and thought I would share a quick tutorial on how to use blendtrees to manage animations. I am not going to go over creating the sprites or splitting them, this assumes you have the animations set up. If you want a quick read on how to do that check out my other post.

Create and Setup the Blend Tree

When you create animations for a sprite, by default Unity will map the state to animations that can be a nightmare to manage if you have a lot of animations. To solve for this you can use a Blend Tree. Delete the animations from the animator and right click in the base layer, select Create State then select From New Blend Tree.

Now create two float parameters, MoveX and MoveY.

With the Blend Tree selected, in the inspector, change the Blend Type to 2D Simple Directional.

Set the parameters to MoveX and MoveY, then add 4 Motion Fields

Drag your down walking animation, right walking animation, walking up animation, and left walking animation to each respective motion field. Below is a table for the values.

MotionPos XPos YAnimation Speed
Down Animation0-11
Right Animation101
Up Animation011
Left Animation-101

Setting Up your Animation Class

This section assumes you already have some sort of player movement class created.

At the top of your class you need to create two read only variables to avoid mistyping the parameters for your Blend Tree if you need to use them for other animations like idle, attack, jump, etc. Otherwise you would need to type it exactly each time and it is prone to mistakes. You will also need access to your animator

...
private readonly int moveX = Animator.StringToHash("MoveX");
private readonly int moveY = Animator.StringToHash("MoveY");

private Animator animator;
...

In your method that reads movement of your player, in my case ReadMovement, check your player movement, if there isn't any movement exit, otherwise update the animator.

...
moveDirection = actions.Movement.Move.ReadValue<Vector2>().normalized;
if(moveDirection == Vector2.zero) return;
animator.SetFloat(moveX,moveDirection.x);
animator.SetFloat(moveY,moveDirection.y);
...

Celebrate

Once you have that added, go back to unity, start your scene and you should see the animations updating as you move the player around. This makes managing animations easier instead of mapping states to animations with arrows all over the editor