# Play sound on animation state exit

I'm trying to figure out how to play a sound effect when a game object leaves a particular state and goes into another. For simplicity, let's just say I want a sound effect to play when the animation for an object transitions from state A to state B, but not the other way around and not for other states. How would I achieve this? I've found information related to playing sound effects when entering a state, but not when exiting from one particular state to another.

To be more specific, I tried implementing this code as a behavior on State A exit:

override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
GameObject self = animator.gameObject;
MyScript myScript = self.GetComponent<MyScript>();
myScript.PlaySFX();
}


But since state A is accessible from any state, I think it is constantly entering state A from itself over and over again. I say this because the sound effect plays repeatedly whenever I am in state A.

• Have you tried using StateMachineBehaviour.OnStateExit? Jul 5 at 19:35
• I considered this, but I can't seem to figure out how to do this properly.
– Mav
Jul 5 at 19:54
• What did you try, and what aspect do you need help with? Jul 5 at 22:16

Check Can Transition To Self in the inspector.