How to loop an audio in unity?
Asked Answered
F

2

5

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);
        ...
}
Fletcherfletcherism answered 21/12, 2019 at 19:53 Comment(0)
C
9
public AudioClip menu;
private AudioSource audioSource;

void Start()
{
    audioSource = GetComponent<AudioSource>();
    audioSource.clip = menu;
    audioSource.loop = true;
    audioSource.Play();
}
Conchoidal answered 21/12, 2019 at 20:13 Comment(0)
G
1

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);
        }
    }
Gunar answered 22/12, 2019 at 0:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.