- Home /
The question is answered, right answer was accepted
How should I code for multiple types of enemy with specific action set?
Greeting all. I just have a quick question regarding how to code for multiple types of enemies for my game. Currently I have a game and I have a script to handle the enemy stats and a script to handle the basic enemy movements. However, now I want to code some special actions for each type of enemies I am adding into the game.
My question is, if each of these enemies will acts differently, does this means I will have to have a specific script for each type of enemy that I am creating so I can code their actions separately? Is there a better way to do this so the number of scripts don't go crazy when the game scales?
some examples of the different action will be like Monster-A performs a strong attack every 3rd attack or Monster-B enhances stats when hit point drops below 50%.
I hope I explain myself clear. Any advice will be great. Thanks!
Best Regard
Answer by highpockets · May 02, 2019 at 09:45 PM
This is where inheritance will come in very handy. Let’s say you have a base abstract class called Enemy where you put some basic functionality in some methods that every enemy will use. But each enemy will have some unique attributes so you make an inherited class for each other type of enemy which defines that enemy’s specific behaviour. Within the child class you have access to everything in the base class, so all of the basic enemy stuff is readily at your disposal.
public abstract class Enemy : MonoBehaviour{
protected void MonsterWalk()
{
}
}
That’s your base class and here is an example of a child class:
public class Ghost : Enemy {
void Update()
{
MonsterWalk();
}
void Disappear()
{
}
void Reappear()
{
}
}
You should really take a look into inheritance as it is a vital part of programming in Unity/C#.. This is just a simple example that doesn’t even scratch the surface, but some tutorials out there will give you a good grasp of how to best take advantage of it.
Cheers
Hi, thanks for the quick reply! I think I didn't explain myself well. I do already have a class for Enemy$$anonymous$$ovement that has the general actions. I just didn't know if I should be creating a child class for each of the different types of enemies and put the specific codes in there or if there is other better ways to handle this.
$$anonymous$$y current project is small so I don't think it will matter but I am just wondering if there is a better practice large scale project.
I would go with the abstract class solution. You will need to create a class for each enemy type because they do different things. $$anonymous$$ake sure you first have good abstract classes in place. If there is overlap between enemy types, you could probably solve that with another abstract class and/or inheritance. Remember, the fewer the code you write, the better it is. You should not be duplicating code. If you are, you are doing something wrong.