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.
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.
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.