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.
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.
To prevent an Audio Clip from restarting, follow these steps:
engineSound
audio clip and drag it from the Project view to populate the Audio Clip parameter of the Audio Source component of AudioObject:using UnityEngine; using System.Collections; using UnityEngine.UI; public class AvoidEarlySoundRestart : MonoBehaviour { public AudioSource audioSource; public Text message; void Update(){ string statusMessage = "Play sound"; if(audioSource.isPlaying) statusMessage = "(sound playing)"; message.text = statusMessage; } // button click handler public void PlaySoundIfNotPlaying(){ if( !audioSource.isPlaying) audioSource.Play(); } }
The Audio Source components have a public readable property isPlaying, which is a Boolean true/false flag, indicating if the sound is currently playing. The text of the button is set to display Play Sound
when the sound is not playing, and (sound playing
) when it is. When the button is clicked, the PlaySoundIfNotPlaying()
method is called. This method uses an if
statement, ensuring that a Play()
message is only sent to the Audio Source component if its isPlaying is false.
3.143.203.96