Getting a reference to an object from a state behaviour

I have a State Behavior walk and Cry.

When “OnStateEnter” fires from the animator, I want to change some properties on the gameObject that is entering the state.

So when the enemy enters the walk state from the State Behavior overriden method, what is the most efficient way to get a reference to this object that has a script “EnemyScript” attached to it?

using UnityEngine;

public class MyStateBehaviour : StateMachineBehaviour
{
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        EnemyScript script = animator.GetComponent<EnemyScript>();
        script.DoSomething();
    }
}

@krupps
You can add a base state behavior script, In other words one that acts on the overall state machine.
You do this by just clicking on the background of the animator to deselect any states (the base layer itself).

You will then see in the inspector you can add a behavior (it’s the only thing you can do here)

This behavior is special because it has additional event hooks and is persistant to the statemachine
making it the perfect place to cache some references and a great place to do higher level
persistent logic to control the state machine.

Hope This Helps.
Enjoy!

Actually a GetComponent is just a cast so it’s really not that bad

// In any Singleton in your game:


public Dictionary EnemyScriptDictionary;


// In EnemyScript:


void OnEnable()
{
if (!Singleton.Instance.EnemyScriptDictionary.ContainsKey(GetComponent()))

        Singleton.Instance.EnemyScriptDictionary.Add(GetComponent<Animator>(), this); 

`` }

void OnDisable()
{
    if (Singleton.Instance.EnemyScriptDictionary.ContainsKey(GetComponent<Animator>()))
    
        Singleton.Instance.EnemyScriptDictionary.Remove(GetComponent<Animator>());
}

// In StateMachineBehaviour:


override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    Singleton.Instance.EnemyScriptDictionary[animator].Chase();
}