Delaying before playing a sound
Sometimes we don't want to play a sound immediately, but after a short delay. For example, we might want to wait a second or two before playing a sound to indicate the slightly delayed onset of a poison drunk or having walked into a spell that weakens the player. For such cases, AudioSource offers the PlayDelayed(...)
method. This recipe illustrates a simple approach for such cases where we do not wish to immediately start playing a sound.
Getting ready
Try this with two audio clips that are several seconds long. We have included two free music clips inside the 04_04
folder.
How to do it...
To schedule a sound to play after a given delay, do the following:
- Create a new Unity 2D project and import the sound clip files.
- Create a GameObject in the scene containing an AudioSource component linked to thePacman Opening SongAudioClip. This can be done in a single step by dragging the music clip from the Project panel into either the Hierarchy or Scene panels.
- Repeat the...