Virtual Methods and Overriding!
Objective: Understanding what virtual methods are and the act of overriding and implementing it into your game.
Did you know, you can inherit classes that are MonoBehavior. In this tutorial we are going to use an example of companion system. To begin we need to create a new C# script “Companion” Keep the class inherit MonoBehavior and define companion.
Now we want to create a cube “Bronn” and attach the pet script.
If you call the speak function the console will print out ‘Speak!’ However, we want Bronn to say “Hello!” We can create a Bronn class and inherits companion. Replace the pet script attached to Bronn with the Bronn script.
Since it inherits companion, it still has its own speak method. What we want to do is take the companion function and override the values. We will need to switch the variable types to protected. To override the speak function you to have use virtual method.
This allows you to override this function from any class that inherits companion. Using public vs protected doesn’t matter for overrides, so long as they match the parent type.
This will call the base implementation of speak. If you played the editor at this point, the console would still read, “Speak!” We can change it from calling the parent class and instead
This is an example of override methods to create behaviors. Let’s continue by creating another cube, “Dog” inherit from companion. Remove the void start and update and override the speak function with “Bark bark!”
On the base class, companion, we want to add the void start method. Speak is a virtual method, it will check all the children that inherit this class and see if any are overriding this. If they are, it is going to call that method.
Now we can run the editor and see in the console will have both “Hello” and “Bark bark”
This is how we can use inheritance to have common shared code and customize it farther. As always, don’t be afraid to experiment with your code, and I’ll see you in the next tutorial!