2D Attack System using Interfaces in Unity
I have the enemies in my game and now it is time to allow the player to attack them.
To start, create a new c# script and call it IDamageable. This will be an interface. Interfaces are similar to class inheritance except for a script that uses an interface must use all components in the interface. A script can also use multiple interfaces.
In the IDamageable script declare it an interface and create a health variable and a damage method.
Go to one of the enemy classes and add the IDamageable interface to the script.
This will force this class to use the health variable and the damage method.
In the Init method, set the Health variable equal to the health variable in the Enemy class.
In the damage method, subtract one from health each time the enemy is hit. If health is less than one destroy the current game object the script is attached to.
To make use of this go to the attack script and create an OnTiggerEnter2D. You will check for an IDamageable component on the collider you hit. if it has one you will call the damage method.
To make sure the enemy is only hit once per swing, create a boolean variable. This variable will be false after the damage method is called. After the damage method is called, call a coroutine to wait for 0.5f seconds and make the variable true. This variable will need to be true to call the damage method again.
If you add a debug statement in the skeleton class after you subtract one from health you will be able to see the health going down.
Now set your enemy's health and you will be ready to test this out.