Richarrd82 Richarrd82 - 2 months ago 16
C# Question

Song picking system

I am trying to do a song picking UI in my project. Everytime u click on a button in the game it sends int to this function. Is there a better way to structure this code so i don't have to write IF statements for every single song?

public void SongPick(int song)
{
if (song == 0)
{
audioSource.clip = musicArray[0];
}
if (song == 1)
{
audioSource.clip = musicArray[1];
}
if (song == 2)
{
audioSource.clip = musicArray[2];
}

audioSource.Play();
string currentMusic = musicArray[song].name;
songName.text = "PLAYING: " + currentMusic;
}

Answer

Assuming song always references the correct index in musicArray you definitely don't need an ever-growing if statement.

public void SongPick(int song) {
    if (song < musicArray.length) {
        audioSource.clip = musicArray[song];    
    }    
    audioSource.Play();
    string currentMusic = musicArray[song].name;
    songName.text = "PLAYING: " + currentMusic;
}
Comments