How to Quickly Add Audio to Your Animations in Unity

Silvio Carréra
Mar 26 · 2 min read

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.

Silvio Carréra

Written by

Not a writer but I like to write, sometimes. English mostly but Portuguese when the mood strikes. Fiction/Game Dev/Life’n’Stuff

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade