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 don't wish to restart the sound. This recipe includes a test, so that an AudioSource component is only sent a Play()
message if it is not currently playing.
To prevent an audio clip from restarting, follow these steps:
AudioObject
, and add an audio source component to this object.// file: AvoidSoundRestart.cs using UnityEngine; public class AvoidSoundRestart : MonoBehaviour{ public AudioSource audioSource; private void OnGUI(){ string statusMessage = "audio source - not playing"; if(audioSource.isPlaying ) statusMessage = "audio source - playing"; GUILayout.Label( statusMessage ); bool buttonWasClicked = GUILayout.Button("send Play() message"); if( buttonWasClicked ) PlaySoundIfNotPlaying(); } private void PlaySoundIfNotPlaying(){ if( !audioSource.isPlaying ) audioSource.Play(); } }
AudioSource
components have a public readable property named isPlaying
, which is a Boolean true/false flag indicating if the sound is currently playing. The PlaySoundIfNotPlaying()
method includes an if
statement ensuring that a Play()
message is only sent to the AudioSource
component if its isPlaying
is false.
3.137.212.71