1
votes

I have a simple sprite sheet that I'm using in a Unity project:

Say hi to Wizzy

It has frames for walking and standing in each of four directions. I've cut the image up using Unity's Sprite Editor and made a separate Animation object for each series, all of which fit neatly into a single animation controller:

enter image description hereenter image description here

I've added the animation controller to an Animator component on a GameObject in my scene. This is where I start running into trouble. I can't for the life of me figure out how to change between the animations in my code.

3

3 Answers

1
votes

You are not supposed to create the connections between your animations in a script. What you do is you create the connections in the Animator and set up variables for if you are standing or walking and in which direction you are going. Then you just edit these variables in a script and the Animator takes care of chosing the right animation.

This video shows it in action: Example

(you see the connections and in the bottom left the variables he set up)

Quick google of "mechanim 2d tutorial" gives you: Tutorial

edit:

Too long for a comment :)

Basically what i would do is create 2 variables, one bool named "Standing" and one Integer named "Direction". Then you make one connection from AnyState to every other state you have(Rightclick on AnyState to make the transitions). Maybe order them in a circle around AnyState.

After this, click on the connections and in the Inspector set the conditions by chosing "Standing", then add one more and set it to "Direction" "Equals" and the number for the direction.

Then in your script somewhere in your Update function you might have something like:

private readonly int UP = 0;

...

if(speed.magnitude > 0.0f)
    Animator.SetBool("Standing", false);
else
    Animator.SetBool("Standing", true);


if( Condition for walking up? )
    Animator.SetInteger("Direction", UP);
if( Condition for walking down? )
    Animator.SetInteger("Direction", DOWN);
...

this might not work directly, but you get the idea. You might want to use a switch for the direction depending on how you set it up.

1
votes

Why even use code? Just hook it all up in the Animator using parameters and just change the parameters as needed.

0
votes

The Animator.CrossFade function will achieve the desired results:

C#:

Animator animator = this.GetComponent<Animator>();
animator.CrossFade("WizzyWalkDown", 0);

It may seem a little excessive, or counter-intuitive, but remember that the AnimationController class was built to make transitions between animations easy. It can still very much be used for simpler animation types like this, though!