No Clutter Object Spawning in Unity

Without organizing our Hierarchy, it could become very cluttered with spawned objects while running or debugging our program. To avoid the clutter, it would be helpful to create some sort of object container to hold the spawned objects.

  • Right click on the “Spawn_Manager” game object in the Hierarchy panel.
  • Click on “Create Empty” to create an empty GameObject and name the empty GameObject “EnemyContainer”.
Create Enemy Container

Now we need to let Spawn_Manager know about the container.

  • Inside the “SpawnManger” script, create a variable for the “Enemy Container” by typing in the following code.

private GameObject _enemyContainer;

Adding _enemyContainer Variable
Note: Be sure to include the [SerializeField] line in order so see it in the Inspector panel in Unity.
  • Back in Unity, click on “Spawn_Manager” game object in the Hierarchy panel.
  • In the Inspector panel, you will see the empty “Enemy Container”. Drag the Enemy Container object from the Hierarchy panel and drop it into the empty slot for Enemy Container.
Dragging Enemy Container

Now we need to be able to hold on to a reference of the spawned (instantiated) object. To do this we will have to create a GameObject variable to hold the instantiated object. We’ll name the GameObject “newEnemy”.

  • Change:
    Instantiate(_enemyPrefab, posToSpawn, Quaternion.identity);
    GameObject newEnemy = Instantiate(_enemyPrefab, posToSpawn, Quaternion.identity);
Create GameObject newEnemy

Now, when we create the new object, we can access it through “_newEnemy”. We can now access the parent object and assign a new parent.

  • Add the following script to your “SpawnManager” script:
    newEnemy.transform.parent = _enemyContainer.transform;
Adding Code to Script

When we run the program in Unity, we will see that every time a new “Enemy” is instantiated, it is added inside the “Enemy Container” object.

Testing the Container

Thank you for reading this article. I hope it was informative and helpful.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
James Hills

James Hills

I am a married father of 5 children. I decided at 13 years of age that I was going to become a Software Developer.