unity random number 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)] // if it's an array
myListOfItems[Random.Range(0, myListOfItems.Count)] // if it's a List
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.
// this is the list we're going to remove picked items from
List<T> tmpList = new List<T>(list);
// this is the list we're going to move items to
List<T> newList = new List<T>();
return newList;
Now we want to loop and move items from one list to the other.
// make sure tmpList isn't already empty
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)
{
// this is the list we're going to remove picked items from
List<T> tmpList = new List<T>(list);
// this is the list we're going to move items to
List<T> newList = new List<T>();
// make sure tmpList isn't already empty
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)