- Home /
The question is answered, right answer was accepted
Int Switch always chooses same value
So... I have here an int which value is 3, and i am using switch
to make it randomly choose one of the three audio sources i have, but for some reason, it literally ALWAYS chooses it's last number. Example: If the int is set to 1, it will play the first audio source. If it is 3, it will play the third. Seriously what the fck? Am i missing something here, or my script is rebelling against me for some reason? I mean, i use the same method on other scripts, and they always work.
Here is the script:
private int randomValue = 1;
private AudioSource[] sources;
void Start()
{
sources = gameObject.GetComponents<AudioSource>();
switch (ramdomValue)
{
case 1:
sources[0].Play();
break;
case 2:
sources[1].Play();
break;
case 3:
sources[2].Play();
break;
}
}
Answer by ThePunisher · May 11, 2017 at 12:00 AM
There may be code missing but I just don't see how you are changing the value of
private int randomValue = 1;
to anything other than the initial value of 1, which would always trigger case 1 and play the AudioSource in element 0. This would explain why it's always playing the same sound.
If you are actually changing the value of randomValue then it's possible that all 3 of your AudioSource components on the object that has this script are all pointing to the same audio asset file.
Edit: Also, not to be rude but a simpler and less error-prone way of doing what you are trying to do would be to do something like the following:
public class Test : MonoBehaviour
{
private AudioSource[] sources;
// Use this for initialization
void Start ()
{
sources = gameObject.GetComponents<AudioSource>();
int randomValue = Random.Range(0, sources.Length);
sources[randomValue].Play();
}
}
Duh, yeah i can't believe i missed that. I feel so dumb right now, i just realized that i completely forgot to use random range and i quickly came here to see if anyone had answered it otherwise i would just delete the question before i would fix it. Anyway, thanks! Gotta go now. Also, yeah i know i could be using something else, i just wanted to test.
Hah, no worries man. It happens to me all the time. Glad to help, good luck!