Playing a random song and removing it from the list

Hi everyone I’m new to the forum so let me know if I did something wrong while making this post. With that out of the way here is my question.

I’m trying to make a script that selects a random song to play and then removes it from the list so that when a next random song is chosen it can’t play the same one again until all songs have been played. I all songs have been played the list will be reset to its original state with all it containing all songs again.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gamemusic : MonoBehaviour
{
    public List<AudioSource> music;
    public List<AudioSource> OGmusic;
    private int rand;
 
    void Start()
    {
        int rand = Random.Range(0, music.Count);
        music[rand].Play();
    }

    void Update()
    {
        if (music[rand].isPlaying == false)
        {
            MusicCheck();
        }
    }

    void MusicCheck()
    {
        music.RemoveAt(rand);
        int rand = Random.Range(0, music.Count);
        music[rand].Play();

        if(music.Count == 0)
        {
            music = OGmusic;
        }
    }
}

The problem is that now unity is saying that I’m using the variabel “rand” before declaring it. I’m sure there is a simple way to fix this but I’ve been fiddling with the code for a while now and haven’t found a solution yet.

Go back and look at your code again. What part of the error message is unclear?

Also, if you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

Am I not already declaring it in “void Start()”? Shouldn’t that be enough? Even is I give the int a number at the beginning of my code when I declare my variables I still get the same error. Btw I updated the post and added code tags thank you for mentioning that.

Time to go review some C#.

The line beginning with int rand is what declares the variable.

You’re using it BEFORE that line, which is exactly what the error says, and it is clear you read it because you paraphrased it.

Ok thank you I finally see what I did wrong. I didn’t understand the difference between “int rand =” and “rand =” but now I do. I just removed the “int” and now it works. Thanks a lot.

Oh yeah, you actually had TWO variables going, the class instance variable on line 9 and the local variable that was causing the error. I didn’t even notice that.

You may wish to use a better name than rand, such as chosenSongIndex or something with at least some semantic meaning.

1 Like