https://s3-us-west-2.amazonaws.com/secure.notion-static.com/13f30ab2-3ed3-4c0a-bc73-b1dc5e8fc704/Random.gif

Description


Variation of animation can add a lot of livelihood to the characters and environments of a game. If an NPC scratches it's nose every two seconds it won't look believable and immersive, throwing couple more idle animations and shuffling them randomly would instantly make our virtual character less "suspicious".

There is no black magic involved in the implementation of such random animation player, but if you are in a stage of implementing loads of different characters and setting up their unique animations you might find yourself tired of rewriting same randomizers for each slightly different case.

But I recently found out about StateMachineBehaviour which made it a breeze to implement quick, reliable and reusable solution! Here's what unity has to say about it:

State machine behaviours are scripts that can be attached to animator states or sub-state machines in an Animator Controller. These can be used to add all sorts of behaviour that is state dependent such as playing sounds whenever you enter a state. They can even be used to make logic state machines which are independent of animation.

Also, to find more tips or just some info on rad projects I'm developing you can find me on twitter: @PetrasMal

Implementation


Script


using UnityEngine;

public class IntParameterRandomSetter: StateMachineBehaviour {
        public string IntParameterName;
        public int StateCount = 0;
        override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
            animator.SetInteger(IntParameterName, Random.Range(0, StateCount));
        }
}

Setup


Setup the animator and add the states you want to shuffle between.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/6dabb4ec-bd29-49b1-b6ba-347cdfefdde6/Untitled.png


Create empty behaviour state that will direct animator to one of your random states: Right-click in an empty animator space → Select "Create State" → Select "Empty"

Make a transition to this newly created state based on your animator setup.