I’m trying to use an ArrayList of 10 strings, randomly choose one, access it, then remove it from a list of available choices.
The issue I’m having is maintaining that unique running list of remaining strings.
Random.Range( 1, myArrayList.Count + 1 ) gives me the proper range but say I have already used item #4…it shouldnt be an available choice. Also what if I’ve used #1…now my range is wrong.
Any ideas on his this logic is managed? I’m writing in C#. TIA.
First of all, arrays and lists in C# start at 0, so your random range should be Random.Range(0, myArrayList.Count).
The easiest way to handle this would be to remove items from myArrayList as you go.
int next = Random.Range(0, myArrayList.Count);
string s = myArrayList[next] as string;
myArrayList.Remove(s);
This code will get one random string out of myArrayList and remove it from the list so that next time it won’t be available.
I would also recommend that you switch from ArrayList to List so you don’t need to cast your objects when you take them out of the list.
1 Like