Abstract Classes in Unity

Chad Gutterman
2 min readJun 11, 2023

--

objective: This article deals with abstract classes in Unity, this being an intermediate subject, I will try to explain it in some detail with examples.

The reason you want to use these classes is to shorten the work load on coding in your program. If you have 50 enemies that each have health, speed, items to drop, ect. You do not want to code this 50 times individually with each enemy class you make. Instead an abstract class can manage this for you.

Here we have an abstract class called enemy. This is no particular enemy, but this script is for all the enemies in the game. Each enemy will have health, speed, and gems. In the attack method I have the key word virtual in the method. This allows me to override the attack method within other enemy scripts so I can have each enemy have their own unique attack. The update method has the word abstract in its title. This forces each enemy to have an update method in its script.

This is a simple example of how to use an abstract class. My moss giant has the monobehavior removed, and in its place is the enemy class. My moss giant will inherit the health, speed, and gems of the enemy class. And I have forced it have an override update method as discussed above. When the attack method is called in start, it will print to the console you attacked. No need to write out an attack method in the moss giant script for it is already done in the enemy class.

Another example of using the enemy class with a spider. The key note here is that I overrided the attack method in this script, and console will print out spider attack.

--

--