- Home /
Unity 2D C# - Creating a Box Out Of Boxes
This is my half finished code
Right now it does 1 line and that line is 10 boxes the 2nd line just goes on until it reaches the max
so it kinda looks like this at the moment
++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++
and its meant to be a 10 by 10 square ++++++++++ ++++++++++ ++++++++++
and so on
can anyone help me do this, I think I am meant to do some sort of loop with the height
//start of spawning location
Vector3 StartPosition = transform.position;
int BlockWidth = 10;
int BlockHeight = 10;
int BlockAdder = 0;
while (BlockAdder < (BlockWidth * BlockHeight)) {
if (BlockAdder == BlockWidth) {
//GroundLayerArrayPositive.Add(1); //Block Type
//GroundLayerArrayPositive.Add(BlockWidth); //X Location
//GroundLayerArrayPositive.Add(BlockHeight); // Y Location
Instantiate(DirtBlock, transform.position = new Vector3(StartPosition.x + 0.5f, StartPosition.y - 0.5f, 0), transform.rotation);
BlockHeight++;
}
else
{
Instantiate(DirtBlock, transform.position = new Vector3(transform.position.x + 0.5f, transform.position.y, 0), transform.rotation);
}
BlockAdder++;
}
If you know the required number of iterations you'd be better off using a for loop, for creating a square use a second nested for loop (or while loop if you prefer).
Your Instantiate statement is somewhat curious too, your second parameter:
transform.position = new Vector3(StartPosition.x + 0.5f, StartPosition.y - 0.5f, 0);
This will create a new Vector3, set the transform.position of the object which has the script attached to it and also set it to the Instantiated DirtBlock. It may be what you're after but I doubt it.
for(int x = 0; x < BlockWidth; x++){
for(int y = 0; y < BlockHeight; y++){
Instantiate (DirtBlock, new Vector3(transform.position.x + (x * 0.5f), transform.position.y + (y * 0.5f), 0);
}
}
I used your code, I had to modify it so it wouldn't have an error and i got this
Instantiate(DirtBlock, transform.position = new Vector3(transform.position.x + (x * 0.5f), transform.position.y + (y * 0.5f), 0), transform.rotation);
And it does this weird wave pattern like an inside out cloud.
Why do you have an "assignment to a variable" as the second parameter of the Instantiate call?
$$anonymous$$aybe assignments can have a return value in C# but in most languages you would get at least a warning from that :P
Depending on what a syntax like that does, it could cause some weirdness as you are moving the reference object every time and then positioning the New object based on the other, moved object.
Try with just
Instantiate (DirtBlock, new Vector3(...
Ins$$anonymous$$d of
Instantiate(DirtBlock, transform.position = new Vector3(...
CrazyNugget's suggestion should work ok. :)
O$$anonymous$$G!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! It worked!!!! Thank you so sos sosososoosososososos much!!!!