Preventing an Audio Clip from restarting if it is already playing
In a game, there may be several different events that cause a sound 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 1362_09_03
folder.
How to do it...
To prevent an Audio Clip from restarting, follow these steps:
Create an Empty GameObject and rename it to AudioObject. Then, add an Audio Source component to this object (in the Component | Audio | Audio Source menu).
Import the
engineSound
audio clip and drag it from the Project view to populate the Audio Clip parameter of the Audio Source component of AudioObject:Create a UI button named PlaySoundButton on the screen and attach the following script to this...