create a function, return random gameObject from an array?
I want create a function that take any array of game Objects and return a random game object. I wrote these:
public GameObject[] items;
items = Resources.LoadAll<GameObject>("Game_Items") as GameObject[];
public GameObject getRandomItem()
{
int randomIndex = Random.Range(0, items.Length);
return items[randomIndex];
}
It works, but only for one array: Items. I want to know how can I modify this function that getRandomItem() takes any array, and return a random item from that array?
Comment
Best Answer
Answer by DoTA_KAMIKADzE · Aug 28, 2015 at 06:26 PM
There you go:
public GameObject getRandomItem(GameObject[] items)
{
return items[Random.Range(0, items.Length)];
}
//example of use:
void SomeFunction()
{
GameObject[] someItems;
someItems = Resources.LoadAll<GameObject>("Game_Items");
GameObject randomItem = getRandomItem(someItems);
}
Your answer
Follow this Question
Related Questions
I'm trying to shuffle an array's order 3 Answers
null array? 0 Answers
Use all variables from array (in Random.Range()) 2 Answers
how to not repeat random array 1 Answer