- Home /
Issues with random music player
I was working on a "radio station", so I made my script, my GUI, everything fine, until I tested the script, I´m not sure what went wrong but you can watch the problem on the video:
I´ve noticed about the IndexOutOfRangeException so the real problem here is why does the song change that way, of course here´s the script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DSN : MonoBehaviour {
public AudioSource Audio;
public AudioClip[] Songs;
public AudioClip[] News;
public AudioClip Estatica;
public Slider Volume;
public Slider Sintonizador;
public Text Station;
public Image VolumeImage;
public Sprite[] VolumeSprites;
void Start () {
}
void Update () {
if(Audio.isPlaying == false && Sintonizador.value > 70f){
int s = Random.Range(0, Songs.Length + 1);
Audio.clip = Songs[s];
Audio.Play();
}
if(Audio.isPlaying == false && Sintonizador.value < 30f){
int r = Random.Range(0, News.Length + 1);
Audio.clip = News[r];
Audio.Play();
}
if(Sintonizador.value < 70f && Sintonizador.value > 30f){
Audio.clip = Estatica;
Audio.loop = true;
Audio.Play();
}else{
Audio.Stop();
Audio.loop = false;
}
Audio.volume = Volume.value;
Station.text = Sintonizador.value.ToString("F1");
if(Volume.value == 0f){VolumeImage.sprite = VolumeSprites[0];}
if(Volume.value > 0f && Volume.value < 0.33f){VolumeImage.sprite = VolumeSprites[1];}
if(Volume.value > 0.33f && Volume.value < 0.66f){VolumeImage.sprite = VolumeSprites[2];}
if(Volume.value > 0.66f){VolumeImage.sprite = VolumeSprites[3];}
}
}
Just to clarify, the array "News" isn´t setted up, so, just focus on the "Song" array
Answer by Wolfrik_Creations · Dec 20, 2016 at 06:29 AM
You're doing:
int s = Random.Range(0, Songs.Length + 1);
That's why the index is out of range, try:
int s = Random.Range(0, Songs.Length);
Yeah, it´s because I read somewhere that if you use Random.Range with an int it will never return the last item in the array, that´s why I put + 1, but if it can work without it, I´ll delete it :)
Yeah... I read about it too... But seems this doesn't apply to var.Lenght (array) var.Count (List).
Thanks for your help, I´ve already fixed it :)