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
MediumBuild a wall of Brick prefabs, 4 wide and 5 high.
- In
Start(), loopcfrom 0 to 3 and, inside it,rfrom 0 to 4. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch11Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsTake Back the NewestDestroyRandom SpawnsRecap: Fireworks6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground