# Random Object in Array

I am using Unity. I have created eight different types of objects, stored in an array, and I am displaying them on the scene in a grid pattern with random order.

The first four objects in the array are red. The player needs to destroy all four red objects to go to the next level.

The code I've writted so far uses the Random.Range method, which chooses objects completely randomly. Sometimes it generates a grid that doesn't contain four red objects, so my player can't destroy them and proceed to the next level.

How do I randomly generate this grid so that it is guaranteed to have exactly four red objects?

Here is my code.

public int gridWidth = 0;
public int gridHeight = 0;
public GameObject[] facePrefab = new GameObject[8];

void Awake()
{
gridHeight = Random.Range (3, 5);
CreateGrid(gridWidth,gridHeight);
}
void CreateGrid(int numX, int numY)
{
for (int x = 0; x < gridHeight; x++) {
for (int y = 0; y < gridWidth; y++) {
GameObject go = Instantiate (facePrefab[Random.Range(0,facePrefab.Length)]) as GameObject;
}
}
}

• I think I understand what you mean... Why not first create the red objects and place them at random positions in your grid and then populate the rest with random objects? – Savlon Nov 15 '14 at 13:32
• I've edited the question in an attempt to make it more readable. Please fix any errors I made in interpreting your original question. – Gregory Avery-Weir Dec 2 '14 at 16:39