Pick random song

For my game I would like to create a playlist for background music that plays in the background. I cannot seem to create an array that chooses a song at random and plays it. Then when the song ends it plays another. I do not want to create another audio source, I simply want to change the song on the audio source.

Edit: Thanks all for the suggestions. I'll look into those sources.

1 Answer

1

you can make something like this:

var myMusic : AudioClip[];

void Update()
{
    if(!audio.isPlaying)
        playRandomMusic();
}

function playRandomMusic()
{
    audio.clip = myMusic[Random.Range(0, myMusic.length)];
    audio.Play();
}

Do I need some kind of audio source on the object I put this script on? I tried just putting the script on a box in the center of the scene but i won't play anything when I start the game.

yes, you have to put your music in the myMusic array in the inspector too.

I'm new to Unity so how exactly would I add something to the inspector?

okay go to the gameObject where u put the script, then expand that script in the inspector, then expand myMusic, set how many music you have, find each of your music in your asset folder then drag each inside the myMusic boxes one by one. then just call the function to play a random music.

Ok I got that working but now when I run it the audio source shows that its sound is switching between all the sounds very fast. In other words, the source is not playing the track for the whole duration.