When you decide to make a game, some elements are bound to be repeated. It doesn’t make sense to rewrite the same parts of code in different scripts. A good idea is to group them according to common factors.
In my case, I’ve examined the enemies of the project I’m working on. All enemies will need a variable for life, one for speed and one for the reward they give after their defeat. It does not concern only the variables but also the methods, the method of attack will exist in all enemies that I will create or the behavior related to their death.
So the idea is to write the main script from which the other scripts will inherit variables and methods.
You just have to pay attention to the keywords to do this. If we want to write a variable that must be inherited we should pay attention to its visibility.
If we put it “private”, the classes that inherit from the main class will not have access to it.
If we leave them “public” they will always be accessible and it is never a recommended choice.
The best choice is to declare them protected so that they are accessible by the classes that inherit from the parent class but they are also private and not externally accessible.
In fact, when you use the “protected” keyword you must always remember to insert the [SerializeField] command to make them visible in the Inspector panel.
This solution allows us to implement methods, using the keyword “virtual” in the parent class and the keyword “override” we can override the method or call the method of the parent class or both. In fact, using the command “base” followed by the method we are calling we recall the body of the method of the parent class.
We can also build methods that must be overridden. I’m talking about Abstract methods that don’t ask us to write the method body in the parent class but we must mandatorily override them in the class that inherited from the main class. This is applicable to all methods including Update not only the methods we created.