What is Inheritance and how do you use it?

So, in scripting we have all used the MonoBehaviour, but did you know, this is in fact a special script you can access, within this script are a bunch of methods that we use on a day to day basis in Unity Engine itself; Looking at you public void Awake();

But why is this special, the script we create does what is called Inherit from it, this means it is considered a child of. So how can we do this ourselves.

Well funnily enough its rather simple, you would create a script, lets call this BaseCharacter, and set your methods, structs, enums and the likes within. Once your script is as you wish, create another script, delete the MonoBehaviour and write instead BaseCharacter.

I shall show an example of both BaseCharacter and a new script that inherits from it:

using UnityEngine;

public class BaseCharacter : MonoBehaviour{
 private string name;

  public void Start(){
 Debug.Log("This is a parent script");
}

public void SetName(string name){
 name = name;
}

}
using UnityEngine;

public class PlayerController : BaseCharacter{
 BaseCharacter baseCharacter;
 public void Update(){
 baseCharacter.SetName(name);
}
}

This example, minimalistic as it is, shows how you can inherit not just events from our BaseCharacter script but also MonoBehaviour through inheritence.

I hope this helps people

The point of inheritance should really be to make use of polymorphism. Good use of inheritance will allow you to use derived types as their base type without having to worry about the derived implementation.

Re-use of code should be a convenient side effect, or when you’re purposely setting up something like a Sandbox Pattern or other similar patterns.

Otherwise common operations can be distilled into extension/utility methods.

I have used a combination of inheritance and as you put “Sandbox Method” which is a term I do not know all too well, the concept I know.

In Unity alone, I use Enumeration Class to switch type of character, it then activates certain aspects of scripts I want, including the UI, which is all set based on the Parent script (which I do call BaseCharacter) I will look into Sandbox Method, it will be interesting to learn, as I am teaching Unity Engine and other engines to people. Perhaps it is another manner of teaching them a principle.

Thank you for your awesome support Spiney, your comments do help :blush: