tzeentch-sorc
tzeentch-sorc

Reputation: 53

How to loop an audio in unity?

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

Upvotes: 5

Views: 19919

Answers (2)

LinusV
LinusV

Reputation: 106

public AudioClip menu;
private AudioSource audioSource;

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

Upvotes: 9

FaTaLL
FaTaLL

Reputation: 511

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

Upvotes: 1

Related Questions