Let’s talk about all the ways you can play and manage audio in your game. Audio makes an interesting topic; it’s relatively easy to get some audio playing in your game, but it’s often unclear how to move from the simplest use case to a slightly more complex one.
This is Unity for Software Engineers, a series for those seeking an accelerated introduction to game development in Unity.
AudioClip, AudioSource, and AudioListener
Let’s start with the three primary constructs involved with playing audio:
- An Audio Clip (in code
AudioClip
) is an asset representing a sound file. - An Audio Source (in code
AudioSource
) is a component on a GameObject. An Audio Source can play Audio Clips at the object’s location for any listeners to hear. - An Audio Listener (in code,
AudioListener
) is a component on a GameObject representing the object receiving (i.e., listening to) audio.
There should be one Audio Listener per scene. Typically, the Audio Listener component will be attached to the Main Camera object by default. You have full control over changing that, but putting your Audio Listener on your Main Camera ends up being a decent pattern to keep.
Each Audio Source has an Audio Clip as a property. An Audio Source can define at most Clip at a time, but you can change the clip on a particular source programmatically during gameplay. Two properties of an Audio Source of immediate interest are Play On Awake, which immediately plays the attached audio clip, and Loop, which loops a clip over and over.
While Audio Sources are associated with objects with locations, an audio source is “2D” (really, more non-dimensional than 2-dimensional) by default, which means the distance between the source and the listener has no impact. Changing the Spatial Blend property of an Audio Source to “3D” will cause its sound level to be affected by the distance between a source and listener.