How to loop an audio in unity?

16.8k Views Asked by At

I was writing a game project on Unity and stumbled with inability to make an audio play infinitely in main menu.

The problem is that the track is played only once (while staying in the menu), when I need it to be repeating until player leaves the menu.

Here is the part of the code where I enable music. I use AudioClip and AudioSource for this.

public AudioClip menu;
private AudioSource audio;

void Start() {
        ...
        audio = GetComponent<AudioSource>();
        audio.loop = true;
        audio.PlayOneShot(menu);
        ...
}
2

There are 2 best solutions below

0
On BEST ANSWER
public AudioClip menu;
private AudioSource audioSource;

void Start()
{
    audioSource = GetComponent<AudioSource>();
    audioSource.clip = menu;
    audioSource.loop = true;
    audioSource.Play();
}
0
On

If you check Loop option in the AudioSource component in the editor, it should work. If not, you messed something up. There is an another way tho, you can loop it like this.

private AudioSource audio;

    void Start()
    {

        StartCoroutine(LoopAudio());
    }

    IEnumerator LoopAudio()
    {
        audio = GetComponent<AudioSource>();
        float length = audio.clip.length;

        while(true)
        {
            audio.Play();
            yield return new WaitForSeconds(length);
        }
    }