Preventing an Audio Clip from restarting if it is already playing
In a game, there may be several different events that cause a particular sound effect to start playing. If the sound is already playing, then in almost all cases, we won't wish to restart the sound. This recipe includes a test, so that an Audio Source component is only sent a Play()
message if it is currently not playing.
Getting ready
Try this with any audio clip that is one second or longer in duration. We have included the engineSound audio clip inside the 04_05
folder.
How to do it...
To prevent an AudioClip from restarting, follow these steps:
- Create a new Unity 2D project and import the sound clip file.
- Create a GameObject in the scene containing an AudioSource component linked to the
AudioClip engineSound
. This can be done in a single step by dragging the music clip from the Project panel into either the Hierarchy or Scene panels. - Uncheck the Play Awake property for the AudioSource component of the engineSound GameObject ...