In my game, there are 3 characters in the scene and all have them have a script,
in the script, there is a variable int damage and a function increseMyDamage(),
which will be called will player get an item in the game.
While as increseMyDamage() do the same things, i.e. increase the variable damage,
hence i will like to use abstract class, so that i need not to edit the function one by one but just changing in the abstract class.
Hence I would like to know how can I do this, as I don’t see much useful result from Google,
with the keyword “unity abstract class”.
public void increaseMyDamage() {
//insert default implementation to be inherited here
}
}
public class ChildClass1 : ParentClass {
//inherits from ParentClass and will use the default implementation
//for increaseMyDamnage()
}
public class ChildClass2 : ParentClass {
public override void increaseMyDamage() {
//override the ParentClass implementation here
}
}
If you don’t want to provide a default implementation for a method in the parent class, remove the curly braces from the method definition, add a semi-colon at the end of the method signature, and add the “abstract” keyword to the signature. For example:
public abstract void increaseMyDamage();
Any class inheriting from this parent class will be force to implement the method.
This doesn’t differ from making a normal abstract class, except that the abstract base will probably inherit from MonoBehaviour
Signature for one abstract class that is also inherited from MonoBehaviour and classes inheriting from it:
public abstract class InGameCharacter : MonoBehaviour { // base part }
public class CustomCharacter : InGameCharacter { // child part }
public class Other : InGameCharacter { // child part }
yes in your case abstract class will work better, an abstract class is the best way to remove duplication of extra code, and restrict the user from creating its instance.
BTW you can also try interfaces, working with interfaces is an awesome experience:)