Script to arrange 3D game object in a grid

GridLayoutGroup component is useful for UI object but won’t help if you want to arrange 3D game objects or 2D sprites. Here is a custom script that will do that for you.

using UnityEngine;

[ExecuteInEditMode]
public class ArrangeInGrid : MonoBehaviour
{
    [SerializeField] private int rows = 2;
    [SerializeField] private int columns = 3;
    [SerializeField] private Vector2 cellSize = new Vector2(1f, 1f);

    void OnValidate()
    {
        ArrangeChildren();
    }

    private void ArrangeChildren()
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            int row = i / columns;
            int column = i % columns;

            Vector3 newPosition = new Vector3(
                column * cellSize.x, // X position
                -row * cellSize.y,   // Y position (negative for downward)
                0                   // Z position (set to 0 for 2D, or customize for 3D)
            );

            transform.GetChild(i).localPosition = newPosition;
        }
    }
}

How It Works

  • rows and columns: These determine the number of rows and columns in the grid.
  • cellSize: This sets the size of each grid cell. Adjusting these values will control the spacing between the objects.

Usage

  1. Attach the Script: Attach this ArrangeInGrid script to any GameObject that has child objects you want to arrange in a grid.
  2. Adjust Parameters: In the Inspector, set the number of rows, columns, and the size of each cell.
  3. Watch the Grid Form: As you adjust the parameters, the child objects will automatically arrange themselves into a grid layout.

Extending to 3D

To extend this to 3D space, you can add another dimension for the Z-axis and modify the newPosition to arrange objects in a 3D grid.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading