In this article, we will convert the Enemy script to an Abstract Class. Changing it in this way will allow us to create more Enemy Types easily without rewriting a large amount of code to make them behave like the standard Enemy but with changes.
To change the Enemy script to an Abstract Class, we need to add the abstract keyword when declaring the class.
Since there will be other scripts inheriting from this script, we can use the protected accessibility on the variables that we want the inheriting scripts to access.
For methods that we want to add on to or override entirely, we use the virtual keyword. Virtual methods have to be accessible from the inheriting scripts, so they need to be public or protected.
Methods that we want to call from the inheriting scripts need to be public or protected.
Now scripts that inherit from the Enemy script will do everything the Enemy script does but allow you to modify the virtual methods. In the ZigZagEnemy script, we modify the CalulateMovement method with the override keyword, telling the method to run everything normally by calling it on the base Enemy script and run the code in this script after.
In the RearFireEnemy script, we tell the Start method of the Enemy script to run normally and call the DetereminePlayerPosition method and the Update method of Enemy to call DetereminePlayerPosition and then run normally. Next, we are overriding the FireLaser method. Depending on where the Player is, we tell it to either run normally or spawn the Laser behind the RearFireEnemy and call PlayClip.
In the Inspector, you can see that the ZigZagEnemy script has all the variables of the inherited Enemy script and the added Side Movement Speed variable.
The last thing we need to do is create another script for the basic Enemy because an Abstract Class can not be added to a GameObject even if it inherits from MonoBehaviour.
Then replace the Enemy script with BasicEnemy on the Enemy Prefab.