Play audio loop by code?

Hi, I use the following code to change songs on a specific scene. How do I loop audio if I play music by code and not directly from the Audio Source Component?

Below is a part of my code, but it only plays the song 1 time and doesn’t loop:

if (lastScene == "MainMenu") {
                audioSource.PlayOneShot (MainMenuSongAU, 0.4f);
                Debug.Log ("Var lastScene is now: " + lastScene);
            } else if (lastScene == "GameStartInfo") {
                audioSource.Stop ();
                audioSource.PlayOneShot (GreenHillsSongAU, 0.7f);
1 Like

PlayOneShot by definition is a one-time playthrough which is gone once it’s completed.

You can set audioSource.loop = true, and then use the normal Play function.

4 Likes

Thanks, got it:

        if (MusicState.GetMusicState () == 1) {
            if (lastScene == "MainMenu") {
                audioSource.Stop ();
                audioSource.loop = true;
                audioSource.clip = MainMenuSongAU;
                audioSource.volume = 0.2f;
                audioSource.Play();

                Debug.Log ("Var lastScene is now: " + lastScene);

            } else if (lastScene == "GameStartInfo") {
                audioSource.Stop ();
                audioSource.loop = true;
                audioSource.clip = GreenHillsSongAU;
                audioSource.volume = 0.8f;
                audioSource.Play();
4 Likes