Phase II: Refactoring my Code

Brian Branch
2 min readJun 18, 2021

--

Doing a bit of refactoring before fully going on to the next feature in the Phase II articles.

First I modified the Spawnmanger script by adding a GameObject array that will hold the different enemy Prefabs that can be spawned. I also added a private int _enemyID which will be randomized to decide which enemy to initialize.

Then I drag the prefabs into the Inspector for the enemies. Currently, it’s just 2, Enemy and SmartEnemy.

This way I can easily expand the game when I add new enemies.

The in the SpawnEnemy() coroutine I set the _enemyID to a random int between 0 and 2 so that I’ll end up with either 0 or 1. Then when I instantiate the enemy I use the _enemiesToSpawn[] array with the _enemyID like below.

The other re-organizing I did was to create a BaseEnemy abstract class and have other enemies inherit from that class. The BaseEnemy class inherits from MonoBehaviour and has all the variables, methods, and calls in the Start() and Update() methods that will be common to all enemies. Below is an idea of how it looks, I’ve collapsed everything except the variables and the Update() method for space consideration in the below screenshot.

This still leaves the BaseEnemy class with a fairly long script but it allows me to create other enemies much more efficiently. I now have a DefaultEnemy script and a SmartEnemy script which both inherit from the base enemy.

Although I had not used inheritance previously, I am now seeing how powerful it can be when you have multiple objects that share the same base values and functionality.

I hope you found this interesting and I’ll be publishing my next article on how I set up the SmartEnemy to detect and fire backward towards the Player soon.

Until then I wish you well on your coding journey.

--

--