Scene-referencing Animator StateMachineBehaviour?

The short question: Is it possible to create an Animator or StateMachineBehaviour (added behavior to a state in an Animator state machine) that can serialize reference scene specific objects?

The explanation: I was trying to create a Button which switches which of two characters you control (and has an animation as a GUI object.) This would involve somewhat complex behavior interacting with objects in the scene. My plan was to have the StateMachineBehaviour script control this, storing the needed objects in serialized variables in the script, and firing the necessary code via OnStateEnter. However, I noticed that I cannot select scene objects in serializing fields in the Behaviour script.

I assume this is because the StateMachineBehaviour object (and presumably the Animator state machine itself) exists across the entire project, rather than specifically in the scene, and thus cannot reference scene-specific objects. If that is true, and immutable, then I assume setting the variables through OnEnable() would suffice, although it is a bit awkward to find the objects instead of serializing them.

I could make another script and have the button call a function in that script via the OnClick() event, but that could lead to desynchronization between the GUI and the actual state, whereas keeping everything controlled within the state machine would keep things tidy.

Thanks for any help!

Spot-on.

In fact if you look at the docs you will see that StateMachineBehaviours are actually ScriptableObjects:
6971372--821873--upload_2021-3-24_21-14-29.png
Therefore they follow all the same rules as ScriptableObjects.

The one nice thing though is that all of the callback functions, e.g. OnStateEnter, OnStateExit, all give you a reference to the Animator. You can then either:

  • Have another MonoBehaviour attached to the same object as the Animator that holds all of the Serialized references you need in publically accessible properties, and just grab that behaviour with GetComponent on the Animator.
  • Navigate to the necessary parts of the hierarchy relatively from the Animator.
2 Likes