- Home /
Randomly Select String from Array
I've got a list of strings contained within a public void, yet any method I use to randomly select one of the strings does not work. Here's the code:
public void rng () {
ArrayList word = new ArrayList();
word.Add("One");
word.Add("Two");
word.Add("Three");
word.Add("Four");
word.Add("Five");
word.Add("Six");
word.Add("Seven");
word.Add("Eight");
word.Add("Nine");
word.Add("Ten");
}
void Start () {
ans = rng[Random.Range(0, rng.Length)];
}
Does anyone have a way I can fix this so the code will assign a string from the list to the variable "ans"? Thanks in advance, -MrFodds
word needs to be a global variable. Call the function to populate the array. Then pick a random position in the array word :
public void rng () {
word = new ArrayList();
word.Add("One");
word.Add("Two");
word.Add("Three");
word.Add("Four");
word.Add("Five");
word.Add("Six");
word.Add("Seven");
word.Add("Eight");
word.Add("Nine");
word.Add("Ten");
}
ArrayList word;
void Start () {
rng();
ans = word[Random.Range(0, word.Length)];
}
I edited the comment. word needs to be a global variable.
I don't use ArrayLists, but this is a great reference : http://wiki.unity3d.com/index.php?title=Which_$$anonymous$$ind_Of_Array_Or_Collection_Should_I_Use?#ArrayLists
So use word.Count
It's not. It's because ArrayList converts everything you put in it to the base type object
. To use anything from it, you have to cast it to the correct type. This is the major reason you don't want to use ArrayList, and use generic lists ins$$anonymous$$d.
I'd always recommend using a generic list over ArrayList (that's List
. They're much safer to use, since they have an associated type.
You need to use generic tags. C#'s built-in List class allows you to define a type for the list, which means you don't need to cast anything, and allows you to keep the typing of your objects while they're in the list. I unfortunately can't directly post an example because the comment system removes anything inside triangular brackets.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Random Number Generated within Array 2 Answers
Distribute terrain in zones 3 Answers