0

My Unity game needs to insert multiple cubes at the start. These positions will be random each time. I am fine with the positioning of them and everything however I can only insert one cube without an error.

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(0, 0, 0);

This code works fine to insert one cube however when I repeat the same TWO lines afterwards it comes up with an error because the variable 'cube' is already defined. I could insert them one by one with different variable names each time however this would be inefficient. I have tried clearing the variable 'cube' so I can then insert a second cube but I still got an 'already defined' error:

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(0, 0, 0);
cube = null;
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);\
cube.transform.position = new Vector3(1, 0, 0);

Does anyone know how to insert a cube an unlimited amount of times without needing to change the variable name?

Thanks.

Note, my code is under void Start()

Andrew
  • 357
  • 2
  • 6
  • 13

1 Answers1

3

To fix the code as you have it written, just remove the first "GameObject" from the lines that have the error:

cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

This is because putting a type in front of the variable is telling the compiler you are trying to declare a new variable at the same time as you are assigning it.

However, the easiest thing to do in this case is use a for loop. You can replace all of the code with this instead:

for(int i = 0; i < 3; i++) 
{
    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    cube.transform.position = new Vector3(0, 0, 0);
}
Excel Kobayashi
  • 578
  • 1
  • 6
  • 19