Seemingly random behaviour when Instantiating numerous Prefabs

Hi, I hope someone can help me here. Just starting out on a project (all new to me this). I’ve built a Ground script which has a public GameCube property. This I’m populating with my ground cube prefab. When I run the game it should build me a ground depending on the public dimensions I’m setting it to. However I’m seeing some strange behaviour whenever it tries to instantiate the final cube in the ground. See below :


Some times missing material


Some times missing and completely out of position.

Here is my code for instantiating the cubes :

for (int y = 0; y < yBricks; y++) {
			for (int x = 0; x < xBricks; x++) {
				Instantiate(brick);
				brick.transform.position = new Vector3(x * 20, 0, y * 20);
				brick.cubeID = count;
				brick.setMaterial(Random.Range(0, 4), count);
				count++;
			}
		}

And instide the Brick class setMaterial function :

public void setMaterial(int rndVal, int cubeCount) {
		print ("Rnd " + rndVal + " Cube : " + cubeID);
		cubeRenderer.material = Instantiate(cubeMaterials[rndVal]);
	}

It’s worth pointing out that the final cube is being passed correct values :

Rnd 2 Cube : 15

The Brick script has a public Array of Materials which I’m dragging to the Prefab in the IDE.

Anyone have any ideas? Many thanks

I don’t think you need to instantiate the new render material if you already have a public array, just access the array and set the material to it,

cubeRenderer.material = cubeMaterials[rndVal];

however, I’m not positive why the Y position of the bricks would move out of place but here’s how i would script it, maybe it’ll make a difference,

GameObject newBrick = Instantiate(brick, new vector3(x20, 0, y20, Quaternion.identity);
newBrick.GetCompoent().cubeID = count;
newBrick.GetComponent().material = cubematerials[rndVal];