Reply To: Getting an Audio clip to loop using Input.GetButton

Forum Archive Getting an Audio clip to loop using Input.GetButton Reply To: Getting an Audio clip to loop using Input.GetButton

#37459
Jonathan Gonzalez
Participant

    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();
             }
            
        }