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:
Create an empty game object named
AudioObject
, and add an audio source component to this object.Drag an audio clip file from the Project view to populate the AudioClip parameter of the AudioSource component of AudioObject.
Add the following script class to the Main Camera:
// file: AvoidSoundRestart.cs using UnityEngine; public class AvoidSoundRestart : MonoBehaviour{ public AudioSource audioSource; private void OnGUI(){ string statusMessage = "audio source - not playing...