Controlling Animations Through C# With The Unity Animator

Bridging the gap between Unity’s built-in animation system and your custom code is pretty simple, but may be daunting when learning for the first time. I’ll try and get you started with the basics.

This is my Player animator

Today‘s Objective: Show you how to quickly and easily connect with and activate animations from code.

Current setup:

On my Player GameObject, I have both an Animator and my custom movement script
I have 3 parameters created. A horizontal speed float, and 2 booleans for which horizontal direction the player is going.
I’ve set some of the transitions between animation nodes to be triggered by one of the Trigger parameters
Animator parameters can be one of 4 types.

The Trigger type is basically a Boolean, but it automatically sets itself to false after 1 frame. So it triggers animations, but doesn’t maintain them.

Accessing through code:

Create an Animator variable, and get the reference in the Awake() method

I have a Vector2 variable “_keyboardInput” which is set to the current movement input from the keyboard, normalized. To send the X movement input to the “VelocityX”, I call the function “SetFloat()” from the Update() method.

SetFloat()” is used because the “VelocityX” parameter is of the type “float”. For other parameter types, equivalent functions exist:

The functions to set other parameter types

For the booleans that control which way the Player’s ship tilts, I use this code. (I do think this could be designed a little better, but haven’t got around to doing anything about it yet)

That’s how to connect and control your animations and Animator component from your own code. Thanks for reading!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.