Spawning Objects in Unity without the Clutter

Gabriel Asay
2 min readMar 19, 2024

--

Spawning objects in Unity can be powerful, but it often leads to clutter in the hierarchy. In this article, I’ll share my strategies for managing and organizing spawning in my project.

In my game, when enemies spawn, the project hierarchy gets cluttered with Enemy objects. Now, let me show you how I’ve solved this problem.

I first start by creating a GameObject nested in my Spawn Manager . I’ve named it Enemy Container . I’ll then open my script for the Spawn Manager and create a new private GameObject variable and name it _enemyContainer . If you would like to know how I wrote this script, please read my previous articles.

public class SpawnManager : MonoBehaviour
{
[SerializeField]
private GameObject _enemyPrefab;

//I've added this variable to store our _enemyContainer GameObject
[SerializeField]
private GameObject _enemyContainer;

void Start()
{
StartCoroutine(SpawnRoutine());
}

IEnumerator SpawnRoutine()
{
while (true)
{
Instantiate(_enemyPrefab, new Vector3(Random.Range(-8.4f, 8.4f), 5f, 0f), Quaternion.identity);
yield return new WaitForSeconds(5.0f);
}
}
}

I will now assign a variable to the Instantiate() method and name it newEnemy.

public class SpawnManager : MonoBehaviour
{
[SerializeField]
private GameObject _enemyPrefab;

//I've added this variable to store our _enemyContainer GameObject
[SerializeField]
private GameObject _enemyContainer;

void Start()
{
StartCoroutine(SpawnRoutine());
}

IEnumerator SpawnRoutine()
{
while (true)
{
GameObject newEnemy = Instantiate(_enemyPrefab, new Vector3(Random.Range(-8.4f, 8.4f), 5f, 0f), Quaternion.identity);
yield return new WaitForSeconds(5.0f);
}
}
}

Finally, this is how we assign the newEnemy parent to _enemyContainer

public class SpawnManager : MonoBehaviour
{
[SerializeField]
private GameObject _enemyPrefab;

//I've added this variable to store our _enemyContainer GameObject
[SerializeField]
private GameObject _enemyContainer;

void Start()
{
StartCoroutine(SpawnRoutine());
}

IEnumerator SpawnRoutine()
{
while (true)
{
GameObject newEnemy = Instantiate(_enemyPrefab, new Vector3(Random.Range(-8.4f, 8.4f), 5f, 0f), Quaternion.identity);
newEnemy.transform.parent = _enemyContainer.transform;
yield return new WaitForSeconds(5.0f);
}
}
}

Now that we have obtained a reference to our instance(s), we can utilize this to assign a new parent object, effectively organizing our hierarchy.

Result:

Perfect! With the enemies spawning in their designated container, our project hierarchy is now much more organized. I’ll be sharing my progress here daily, so if you’re curious about where this project is headed, stay tuned and happy coding!

--

--