Spawn in a Grid
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 50 of 67.
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
MediumBuild a brick wall from the Brick prefab, 4 bricks wide and 5 rows high, standing on the ground. A brick is 1 unit wide and 0.5 tall.
- The 4 columns are at x = -1.5, -0.5, 0.5 and 1.5.
- The bottom row rests on the ground, so its bricks are at y = 0.25. Each row is 0.5 above the one below it.
- Every brick is at z = 0, has no rotation and is a child of the Wall, the object this script is on.
Press Play to see the wall, 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch9Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsDestroyRandom SpawnsRecap: Fireworks