Using inheritance in Unity for better code re-use

January 08, 2016

In previous posts regarding Unity, I’ve made the comment that I’m quite new to Unity… but I’m not new to C#, and have been a little surprised regarding the apparent lack of code re-use through inheritance and polymorphism in scripting examples that I’ve seen. So much so, that I started to assume that, for some reason, this wasn’t possible in Unity.

It is. I was looking for an architecture like this:

UnityArchitecture

As an experiment, I created a base script:



public class BaseScript : MonoBehaviour
{
    public virtual void RunStart() { }
    public virtual void RunUpdate() { }

    void Start ()
    {
        RunStart();
    }
	
    void Update ()
    {
        RunUpdate();
    }

    void OnCollisionEnter(Collision collision)
    {
        StandardCollision(collision);
    }


You get the idea. I handle the standard functions, and then provide either some default functionality, or none, and allow the child to override. Inherit as you would for any base class:



public class MyScript : BaseScript
{
    public override void RunStart()
    {
        base.RunStart();

As you would expect from any C# / .NET similar structure, you reference in the child script, and you get the base functionality.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024