- Home /
When creating a 2D array as a grid of cubes they are all the same colour,My array of gameObjects are all the same colour, even when I set them differently
I am trying to display a 2D array of 1s and 0s as cubes, which are either green or white. However, all of the cubes are the colour of the first one, so if grid[0,0] == 1 all of the cubes will be green. Here is my code:
for (int i = 0; i < width; i++) // draws grid
{
for (int u = 0; u < height; u++)
{
if(grid[i,u] == 1)
{
point = Instantiate(onePrefab);
Vector3 pos = new Vector3(i, u, 0);
point.localPosition = pos;
}
else if (grid[i,u] == 0)
{
point = Instantiate(zeroPrefab);
Vector3 pos = new Vector3(i, u, 0);
point.localPosition = pos;
}
}
}
onePrefab is a prefab with a green material
zeroPrefab is a prefab with a white material
Are they using the same material? $$anonymous$$aterials are assets, so you change it for one object and it automatically gets changed for all objects. It might explain why all your cubes are getting their color set at the same time
Answer by ShadyProductions · Feb 05, 2018 at 05:26 PM
Are you very sure you set them up correctly in the inspector? Perhaps there are only 1 values in the grid, Try add a debug line in both if's and check if both are being called. Or take a look at the array object in debug mode
Answer by e1d1w1a1r1d1 · Feb 05, 2018 at 06:44 PM
It seems that the grid did only contain only 1s or 0s like you suggested, and changing System.Random.Next(0,2)
to Unity.Random.Range0,2)
solved the problem.
Thank you!
Using the .net variant of Random should work fine too aslong as you only create one instance
public Random Random;
private void Start() {
Random = new Random();
}
then you can call it like Random.Next(0,2) The issue you encountered is probably because you made a new instance of Random class every loop, which would give u probably the same result.