Hi, I’ve got an array storing 6 GameObjects and I want to create 3 new arrays, each one containing 2 random GameObjects from the main one.
Example - how I want it to be:
var mainArray : GameObject[] = [obj1, obj2, obj3, obj4, obj5, obj6];
var firstPair : GameObject[];
var secondPair : GameObject[];
var thirdPair : GameObject[];
function Start() {
firstPair = 2 random objs from mainArray;
secondPair = 2 random objs except the first pair;
thirdPair = 2 random objs except the first and the second pair;
}
One solution is to shuffle the array and assign them in order from the shuffled array:
var mainArray : GameObject[] = [obj1, obj2, obj3, obj4, obj5, obj6];
var firstPair : GameObject[] = new GameObject[2];
var secondPair : GameObject[] = new GameObject[2];
var thirdPair : GameObject[] = new GameObject[2];
function Start() {
var temp : GameObject;
for (var i : int = 0; i < mainArray.Length - 1; i++) {
var ii : int = Random.Range(i, mainArray.Length);
var temp = mainArray*;*
firstPair[0] = mainArray[0]; firstPair[1] = mainArray[1]; secondPair[0] = mainArray[2]; secondPair[1] = mainArray[3]; thirdPair[0] = mainArray[4]; thirdPair[1] = mainArray[5]; } Alternately, you can put the game objects in a generic List and pull them out at random, deleting them from the list as each is used.
I wouldnt like to write code if it is not neccessary but i will write with text how would i do it:
1, make a list with the values 1,2,3,4,5,6
for(int i = 1; i <=3; ++i) //if i==1 then add to firstPair etc... i will refer the current array with the name yourCurrentArray in the loop
{
for(int j = 0; j<2; ++j)
{
2, get a random index between 0 and list.length
3, yourCurrentArray[j] = mainArray[random index]
4, remove mainArray[random index]
}
}