Playing different one-off sound effects with a single AudioSource component
As we’ve seen in the recipes at the beginning of this chapter, the basics of playing a sound are very straightforward in Unity – by 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 that you can then reuse to play different sound effects. That is what we’ll do in this recipe.
Getting ready
Try out this recipe using any short audio clip that is less than one second in duration. You can also find several Pacman game sound clips inside the 04_02
folder.
How to do it...
To play multiple sounds using the same AudioSource
component, perform the following steps:
- Create a new Unity 2D project and import the sound clip files.
- Create a C# script class, called
SoundPlayer
, in a new...