Let’s see how to play sounds in Unity, either automatically when you enter the game mode, or by playing a sound using a C# Script. To achieve this we need an AudioListener component in the scene (usually assigned to the main camera) and the AudioSource component with the audio clip we want to play.
Procedure for playing a sound in Unity at the start of the game
1. Create a GameObject and in the inspector assign the AudioSource component (Add Component button).
2. Configure the AudioSource component with the “Play On Awake” option activated and the rest of the parameters configured as you like (see below for the different options).
3. When you enter the game mode, the sound will start playing automatically with the parameters set.
Procedure to play a sound in Unity from a Script
1. Create a GameObject and in the inspector assign the AudioSource component (Add Component button). Deactivate the “Play on Awake” option and configure the other parameters as you wish.
2. Create a Script to control the start of the sound, the volume, the end, among other actions. Assign this Script to the same GameObject that has the AudioSource component.
3. In the script define a reference for the AudioSource object and find it in the Start method using GetComponent<>().
4. Define a public function to play the sound from any other script, within this function execute the instruction: “audioSource.Play()”.
5. Detect the proper event in which the sound should be played and execute the play function defined in the audio script.
AudioSource component configuration
The AudioSource component has many adjustable parameters to achieve different results with our sounds. In the following image we see what the AudioSource component looks like in the inspector in Unity.
To start with, you can manually assign the sound you want to play by dragging it to the AudioClip field. This can also be done from a script with the instruction “audioSource.clip=aClip;”, being “audioSource” the reference of the AudioSource component of the inspector and “aClip” a field that contains the reference of some sound.
Then we can mute the sound and adjust the volume. Enable the “Play On Awake” option so that the sound is played as soon as the GameObject enters the enabled state. The Loop option makes the sound play again when it is finished.
The Spatial Blend is a parameter that allows us to adjust if it is a background sound or a sound that depends on the distance between the AudioSource and the AudioListener. If we put the indicator in 3D, we will obtain a stereo sound whose volume and distribution in the headphones will depend on the position of the source. Within the 3D Sound Settings you can adjust parameters related to this.