Changing Animator State during run-time via scripting?

Hi all,

I’m trying to figure out how to change the animator state during run-time via scripting.

I am not interested in any blending or transitions, simple switching between states and start each animation from the beginning. If necessary I can reload the scene in between, and I have about 200 animator states.

So far, I’ve identified the following functions that can achieve this during run-time, but they are limited to the Unity Editor:

UnityEditorInternal.AnimatorController
UnityEditorInternal.StateMachine
UnityEditorInternal.State

Any advice on how this can be achieved without the above (i.e. for a build)?

Thanks for your time.

How about

myAnimator.Play("MyState");

If the transitions between states depend on the values of parameters then you can use a script to set the values of those parameters and thus change the states.

Thanks for the answers.

myAnimator.Play works brilliantly!

but I need to know the name of the state I want to play in this case…

  • is there anyway I can get a list of available states in the Animator?

I was looking at this thread previously

Not at runtime, no. You can store those names in the Editor, and re-use them later, but you cannot retrieve them while the game is running.

Have a look at this thread in the Assets forum: Animator Access - Generate State & Parameter Hash IDs Smoothly

The generated code contains a member called stateDictionary. It’s a HashTable with the hash IDs as keys and the state names as values. Provided that you like to sue the generator, the following code will do the job:

    ExamplePlayerAnimatorAccess anim = GetComponent<ExamplePlayerAnimatorAccess> ();
    ICollection stateIDs = anim.stateDictionary.Keys;
    ICollection stateNames = anim.stateDictionary.Values;

There are some more convenience methods for checking a state or getting a name by ID.