How to Quickly Add Audio to Your Animations in Unity
Unity offers a bunch of ways which you can structure your code. Lately I realized how I always separated audio and animation. With characters I always had to sync them up. Play attack animation then play attack audio.
Why not add the audio straight to your animation?
Enter StateMachineBehaviour. Unity’s animator allows you to add scripts to each state. This specific type of script receives nifty callbacks to hook things up. Audio fits right into it.
You can set up multiple AudioClips so it iterates through them each time. Handy for things like footsteps. Also, you can configure a desired delay and also set a frequency on the update method.
Let’s look at how the states are configured.
For the Walking State we check the UseMutiple to add more than one AudioClip. The OnUpdate condition has a frequency option of how often you want it to trigger. The script will iterate through the audio clips you added while you remain in that state and the condition is met.
For the Attacking State we set it the condition to OnEnter since we only want it to play once per animation play. The delay is to get the timing right with the animation.
Download here to get things going.