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
Answer by Soos621 · Nov 11, 2015 at 06:57 PM
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(x*20, 0, y*20, Quaternion.identity); newBrick.GetCompoent().cubeID = count; newBrick.GetComponent().material = cubematerials[rndVal];
Thanks for the reply Soos621.
By instantiating the brick different didn't make any difference however by just referencing the material rather than instantiating a new one seems to have fixed the issue. Thanks a lot.
Your answer
Follow this Question
Related Questions
Instantiate screenshots from camera *Realtime* 0 Answers
*Solved* Loop instantiating objects causes my Unity Editor to crash 1 Answer
Instantiate particle system attached to object 1 Answer
How to instantiate bullets in multiple transforms 1 Answer
Destroy instatiate object on trigger enter / collision,destroy instantiate prefab on trigger enter 0 Answers