Adding Audio to 2D Game
Objective: Add audio effect on pressing menu buttons and background music in game.
In game audio requires two objects, an audio listener and an audio source. The audio listener is on the main camera, but does not need be. Within the Main_Menu scene create an empty game object named AudioSource, and add an audio source component. Uncheck play on awake, and drag Menu_Select_V1 audio file into the Audio Clip box. The position of this AudioSource is placed at the same location as the main camera; however, it could be placed to the right or left/near or far to give 3D positional sound effects.
Within the MainMenu script on the Canvas, create a new variable _audioSource, using [SerializeField] assign it in the inspector.
Within void Start(), check to see if _audioSource has been assigned, if not throw an error.
The buttons are set to call a method On Press(), so to play the sound add the _audioSource.Play() line of C# code. The buttons now have a sound effects.
Now as the Game scene starts, background music is used to set the ambiance. Once again consider where the audio listener will be and where the audio source for the background music should be. The audio listener is still on the main camera, but the main camera moves with the player. Since the background music should be at a constant volume without direction, add an audio source component to the main camera. Assign the audio clip, Through the Mist, to this audio source, setting to play on awake and loop.
The addition of this audio track background music quickens the heart and enhances the game experience. Audio is an essential element of any game.
This article uses assets for GameDevHQ Filebase and Unity Asset Store’s Colossal Game Music Collection.