No Clutter Object Spawning in Unity
Cleaning Up the Spawn Manager
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”.
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;
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.
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”.
Instantiate(_enemyPrefab, posToSpawn, Quaternion.identity);
GameObject newEnemy = Instantiate(_enemyPrefab, posToSpawn, Quaternion.identity);
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;
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.