0
\$\begingroup\$

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.

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

1 Answer 1

0
\$\begingroup\$

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.

Check Can Transition To Self in the inspector.

enter image description here

\$\endgroup\$
1
  • \$\begingroup\$ It sounds more like he would want to uncheck that option, since he doesn't want the sound effect to keep playing over and over. \$\endgroup\$
    – Kevin
    Jul 7 at 22:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .