Menu
CoddyTech

Spawn in a Grid

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 64 of 85.

A loop inside a loop visits every cell of a grid: the outer loop picks a column, the inner loop walks along it. Put an Instantiate inside and every cell gets an object. This builds a 3 by 3 floor from tiles that are 2 units wide, so the tiles go 2 units apart:

public GameObject tilePrefab;

void Start()
{
    for (int x = 0; x < 3; x++)
    {
        for (int z = 0; z < 3; z++)
        {
            Vector3 spot = new Vector3(x * 2, 0, z * 2);
            Instantiate(tilePrefab, spot, Quaternion.identity, transform);
        }
    }
}

The tiles land at x = 0, 2, 4 and z = 0, 2, 4: nine of them, from (0, 0, 0) to (4, 0, 4). The loops run in Start(), once. In Update() they would add nine more tiles on every frame.

The fourth argument is a parent. Nine loose Tile(Clone) objects would clutter the Hierarchy; passing transform files them under the object this script is on, the Floor, so they can be folded away, moved together or deleted together. The position you pass is still a world position.

challenge icon

Challenge

Medium

Build a wall of Brick prefabs, 4 wide and 5 high.

  1. In Start(), loop c from 0 to 3 and, inside it, r from 0 to 4.
  2. In the inner loop, call Instantiate(brickPrefab, new Vector3(-1.5f + c, 0.25f + r * 0.5f, 0), Quaternion.identity, transform). The last argument makes each brick a child of the Wall.

Press Play: a wall of 20 bricks stands on the ground. Then Check.

Try it yourself

using UnityEngine;

public class WallBuilder : MonoBehaviour
{
    public GameObject brickPrefab;

    void Start()
    {
        // 4 columns by 5 rows of bricks, each a child of this Wall
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground