Playing different one-off sound effects with a single AudioSource component
The basics of playing a sound are very straightforward in Unity (adding an AudioSource component to a GameObject and linking it to an AudioClip sound file). For simple sound effects such as short, one-off plays of pickup confirmation noises, it's useful to have a single AudioSource component and reuse it to play different sound effects – which is what we'll do in this recipe.
Getting ready
Try this with any short audio clip that is less than one second in duration. We have included some classic Pacman game sound clips inside the 04_01
folder.
How to do it...
To play multiple sounds using the same AudioSource component, do the following:
- Create a new Unity 2D project and import the sound clip files.
- Create a C# script class,
PlaySound
s, in a new folder,_Scripts
, containing the following code, and add an instance as a scripted component to the Main Camera:
using UnityEngine; [RequireComponent(typeof(AudioSource))] public...