Getting an Audio clip to loop using Input.GetButton

Just trying to get a clip to play and wait til it's done playing before trying to start again. Not sure the kinda code to use as I'm still new to unity and coding really.

note:I'm going through the programming bootcamp course, and doing the "Creating a Fixed Turret " currently.

ex;


if(Input.GetButton("Fire1"))
{
    audioclip.Play()
  //Somekind of Wait function or loop function instead of .Play()
}

  • Jonathan Gonzalez(jgonzalez) replied

    There are a few ways to do it, but essentially they're the same general logic:


    public AudioSource aud;
        void Update () {
            if(Input.GetButton("Fire1"))
            {
                aud.enabled = true;
                aud.loop = true;
            }
            else
            {
                aud.enabled = false;
                aud.loop = false;
            }
            
        }
    


    This way you're enabling the audio source only when you're holding down Fire1, when released it'll disable the audio source and stop the looping. The looping portion doesn't need to be in the script as you can enable it on the audio source itself, and just enable and disable the audio source when holding down the button and it'll do the same thing. Writing it in the script just ensures it loops even if you forget to check it on the component. Another way is by checking if the audio clip is playing:

    void AudioLoop ()
        {
            if(Input.GetButton("Fire1") && !aud.isPlaying)
             {    
                 aud.Play();
             }
             else if(Input.GetButtonUp("Fire1"))
             {
                 aud.Stop();
             }
            
        }