2D Galaxy Shooter: Enemy Spawn Manager.
Hello everyone! Today I managed to implement a Spawn Manager so that our enemies instantiate randomly from above within a certain amount of time. I created the enemy and its movement logic on the last progress update. Now it needs a spawn system to make the game fun!
So I learned how to create a spawn system with the use of coroutines! It is amazing what Unity offers. I can only imagine what else is there for me to learn!
A coroutine is a special kind of function that pauses the execution of code/event for a specific amount of time, then continues where it had left off.
I used a coroutine to control the time when to instantiate a game object.
private IEnumerator SpawnRoutine()
{
while (!_stopSpawning)
{
float randomX = Random.Range(-11, 11);
Vector3 randomXposition = new Vector3(randomX, 8, 0); GameObject enemyInstance = Instantiate(_enemyPrefab, randomXposition, Quaternion.identity); enemyInstance.transform.parent = _enemyContainer.transform; yield return new WaitForSeconds(_spawnTime);
}
}
We called the coroutine in the Start()
function of the SpawnManager script to make it work!
Simple enough, the enemy instance will keep spawning from above and recycle itself if not destroyed.
I also learned how to declutter my hierarchy panel in the Unity IDE.
enemyInstance.transform.parent = _enemyContainer.transform;
By grabbing the enemyInstance
transform parent and assigning it to a game object transform, we are saying for every instance of the enemy to relocate to the other objects transform, so it becomes a child object.
Script communication is becoming a lot easier thanks to the way Jonathan Wienberg teaches.
So this concludes the update! I will work on converting the prototype into finished 2D assets next!
Thank you for reading! :)