- Home /
Generating a grid of cubes with space between.
So I was wondering what would be the best way to generate a grid on the X and Z axis with say 5 X and Z Units between eachother? So how would I go about doing this?
Thank you for any help! -Devon
Answer by Addyarb · Apr 18, 2016 at 01:15 AM
Considering this is the first google answer that relates to this question, I figured it's worth answering properly.
Here is some example code to get a space between your grid items!
The magic happens on this line: newRoom.transform.position = new Vector3(x size.x, z size.x, y * size.x);
What we're doing is multiplying our grid item [Read: Cube]'s position by an incremented value. In other words, we're adding a number to the position that increases each time we add a cube.
size.x (in this case) could be anything that gets incremented during the for loop.
Feel free to paste this into the start function/method of a new script and play around with it. I've added the random generation of colors for the cubes to make things more visual.
Vector3 size = new Vector3 (5,5,1); //This is the size of our cube-grid. (5x5x1)
for (int x = 0; x < size.x; x++)
{
for (int y = 0; y < size.y; y++)
{
for (int z = 0; z < size.z; z++)
{
GameObject newRoom = GameObject.CreatePrimitive(PrimitiveType.Cube);
newRoom.name = (x > y) ? "x" + x : "y" + y;
newRoom.transform.position = new Vector3(x * size.x, z * size.x, y * size.x);
newRoom.GetComponent<Renderer>().material.color = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
newRoom.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
newRoom.transform.SetParent(transform);
}
}
}
}
Answer by IMTRIGGERHAPPY9 · Nov 07, 2011 at 05:15 AM
using for statements within each other with an instantiation at the end... you should be able to come up with the rest...
or at least start making your own code instead of asking others to make your game for you
I understand that I'm asking about logic, not code itself.
well like i said use two for loops one nested inside another with your instantation placement being the size of your cube for example i have.
Instantiate(instantiateObject, Vector3(x .5,0,y .5), Quaternion.identity);
this is at the end of my for loop and my first loop is using the letter x and the second is using y then x * the size of your cube on the x axis will add a cube exactly one spot away, same going for the y so just put this at the end of your two loops