You can use code to procedurally generate copies of a prefabAn asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary in a particular configuration. The following example creates a wall of block prefab instances.
To create a wall of blocks, you must first have a block prefab asset to create the wall with.
Assets
folder (Project tab) More infoBlock
.Create a MonoBehaviour script and name it Wall
. Add the following code into the Wall
script:
using UnityEngine;
public class Wall : MonoBehaviour
{
public GameObject block;
public int width = 10;
public int height = 4;
void Start()
{
for (int y=0; y<height; ++y)
{
for (int x=0; x<width; ++x)
{
Instantiate(block, transform.position + offset, Quaternion.identity);
}
}
}
}
Wall
script to the empty GameObject.Block
prefab asset into the Block field,Block
prefab.You can also use code to place prefabs in a grid or other configurations. The following example places the cubes in a circular formation:
using UnityEngine;
public class CircleFormation : MonoBehaviour
{
// Instantiates prefabs in a circle formation
public GameObject prefab;
public int numberOfObjects = 20;
public float radius = 5f;
void Start()
{
for (int i = 0; i < numberOfObjects; i++)
{
float angle = i * Mathf.PI * 2 / numberOfObjects;
float x = Mathf.Cos(angle) * radius;
float z = Mathf.Sin(angle) * radius;
Vector3 pos = transform.position + new Vector3(x, 0, z);
float angleDegrees = -angle*Mathf.Rad2Deg;
Quaternion rot = Quaternion.Euler(0, angleDegrees, 0);
Instantiate(prefab, pos, rot);
}
}
}
When you attach the script to an empty GameObject and enter Play mode, Unity generates the cubes in the following formation: