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 ...
Get Unity 5.x Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.