unity random object from list code example
Example 1: unity random object from list
that's a good question. Randomly pick one item from a list is easy. You can simply do something like :
myListOfItems[Random.Range(0, myListOfItems.Length)]
myListOfItems[Random.Range(0, myListOfItems.Count)]
But picking a given number of items from a list is a bit more interesting.
Let me give this a try and explain through it. Let's begin with the method signature (our goal).
public static List<T> GetRandomItemsFromList<T> (List<T> list, int number)
This will be a generic method, with type T so that it can work with a list of anything. It will take a list, and a number of items to pick for parameters. Then, we want to duplicate the input list, so that we can remove items from it as we add them to a new list. Eventually, we want to return the new list.
List<T> tmpList = new List<T>(list);
List<T> newList = new List<T>();
return newList;
Now we want to loop and move items from one list to the other.
while (newList.Count < number && tmpList.Count > 0)
{
int index = Random.Range(0, tmpList.Count);
newList.Add(tmpList[index]);
tmpList.RemoveAt(index);
}
So, here's the whole method :
public static List<T> GetRandomItemsFromList<T> (List<T> list, int number)
{
List<T> tmpList = new List<T>(list);
List<T> newList = new List<T>();
while (newList.Count < number && tmpList.Count > 0)
{
int index = Random.Range(0, tmpList.Count);
newList.Add(tmpList[index]);
tmpList.RemoveAt(index);
}
return newList;
}
And this is how to use it :
List<Item> randomItems = GetRandomItemsFromList<Item> (allItems, 5);
Example 2: unity random object from list
public static List<T> GetRandomItemsFromList<T> (List<T> list, int number)