Unity: Scripting sound effects
We know how to play a looped background music, but what about sounds that play when an action occurs? Let’s take a look at setting up the laser sound.
First we need to add an audio source to the Player object. We also want to uncheck ‘Play On Awake’ as we need to script when sounds are played.
Next we need to alter our Player script.
We add a an AudioClip for the laser sound, and one for the AudioSource.
We use GetComponent<> to get the Audio Source at Start() and check for null.
In the shooting method, in both of our if else-if statements we assign the laser clip to the Audio Source then play the assigned clip. This will allow us to use the same Audio Source for different clips in future if needed. If we find that we only use the laser sound for the Player’s Audio Source, then we can assign this in Start() later on.
Back in Unity we assign our laser sound to the Laser Audio Clip on our player.
Now when we play the game, this scene sounds like a fierce space battle rather than a silent movie!
This same process can easily be repeated for powerups and explosions as well.