Skip to content

Instantly share code, notes, and snippets.

@FleshMobProductions
Created June 17, 2022 20:52
Show Gist options
  • Save FleshMobProductions/1cf91db70629a7329f02b07d88b80ed9 to your computer and use it in GitHub Desktop.
Save FleshMobProductions/1cf91db70629a7329f02b07d88b80ed9 to your computer and use it in GitHub Desktop.
Script for spawning a number of prefabs in a grid formation in Unity. Place it on an GameObject, right click on the component in the inspector and select "Spawn Elements" to run the spawn method
using UnityEngine;
namespace FMPUtils
{
public class ObjectSpawner3DGrid : MonoBehaviour
{
[SerializeField] GameObject spawnPrefab;
[SerializeField] Transform spawnParent;
[SerializeField] Vector3 startPosition;
[SerializeField] Vector3 xUnit = new Vector3(1f, 0f, 0f);
[SerializeField] Vector3 yUnit = new Vector3(0f, 0f, 1f);
[SerializeField] Vector3 zUnit = new Vector3(0f, 1f, 0f);
[SerializeField] int elementsToSpawn;
[SerializeField] Vector3Int cellSize;
[ContextMenu("Spawn Elements")]
private void SpawnElements()
{
int rowWidth = cellSize.x;
int rowHeight = cellSize.y;
int widthXHeight = rowWidth * rowHeight;
for (int i = 0; i < elementsToSpawn; i++)
{
int z = i / widthXHeight;
int xySubIndex = i % widthXHeight;
int y = xySubIndex / rowWidth;
int x = xySubIndex % rowWidth;
Vector3 spawnPos = startPosition + z * zUnit + y * yUnit + x * xUnit;
var objectInstance = Instantiate(spawnPrefab, spawnPos, Quaternion.identity, spawnParent);
#if UNITY_EDITOR
UnityEditor.Undo.RegisterCreatedObjectUndo(objectInstance, $"Spawn grid element at index {x}, {y}, {z} and position {spawnPos}");
#endif
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment