Z
Z
Zimaell2020-12-11 13:58:32
C++ / C#
Zimaell, 2020-12-11 13:58:32

How to get a random element of a list?

given a list

private List<string> Combinations = new List<string>();

items added to the list
Combinations.Add("111");
Combinations.Add("222");
Combinations.Add("333");

I want to get a random element
string Comb = Combinations[UnityEngine.Random.Range(0, Combinations.Length)];

writes
'List' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'List' could be found (are you missing a using directive or an assembly reference?)

that is, that the list does not have such a property as length, I used this method on an array and not a list, as I understand it, with a list, you need to get a random element differently, tell me how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soloveid, 2020-12-11
@Zimaell

List has a Count property, use it.
PS Well, in the comment to the Random.Range method it is written that both elements can be returned, so you should write like this

string Comb = Combinations[UnityEngine.Random.Range(0, Combinations.Count - 1)];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question