Preventing the AudioClip from restarting if 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 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.

Getting ready

Try this with any audio clip that is one second or longer in duration.

How to do it...

To prevent an audio clip from restarting, follow these steps:

  1. Create an empty game object named AudioObject, and add an audio source component to this object.
  2. Drag an audio clip file from the Project view to populate the AudioClip parameter of the AudioSource component of AudioObject.
  3. 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";
        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();
      }
    }
  4. With the Main Camera selected in the Hierarchy view, drag AudioObject into the Inspector for the public AudioSource variable.

How it works...

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.

See also

  • The Waiting for audio to finish before auto-destructing an object recipe.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.126