Spacing out objects evenly in Unity
In my latest game, I wanted to place windows evenly on a building. I had a window prefab, and wanted to place dozens of them. Sure I could Cmd+D and duplicate them, then input their X and Y values manually, but I figured there should be a faster way to do it.
Grid Layout
I quickly found posts about the Grid Layout. This video shows how to do it quite simply. However, when I tried it in my scene, nothing happened. Unfortunately, it turns out that this Component only works on 2D elements, not 3D, as cited in this post.
Script
So the only way besides doing it manually is to write a script that instantiates the windows at the desired intervals. In its most basic form, it looks like this:
using UnityEngine;
public class Wall : MonoBehaviour
{
public GameObject windowPrefab;
// Start is called before the first frame update
void Start()
{
for (int i = -5; i < 5; i++)
{
for (int j = -5; j < 5; j++)
{
var window = Instantiate(windowPrefab, transform, false);
window.transform.Translate(10 * i * Vector3.forward + 10 * j * Vector3.right);
}
}
}
}
Passing transform
makes the window a child of the Wall, and passing false
means it gets positioned in local space (not in world space). There is no way to pass a local position when instantiating, hence the positioning with window.transform.Translate
.
I'd like to be able to set the number of columns and rows, then let the script automatically space out the windows based on the parent's size. But I don't feel like messing with transforms right now. So I'll keep hardcoding all the values.