Does Unity support Inheritance and Subclassing?

If I have a few different characters/objects in my game that all share some common behavior, can I use inheritance to centralize the common behavior into a base class? Or do you recommend another approach?

To give a simple example, I might want to have a character controlled by the player, and other characters with similar behavior that are controlled by an AI routine.

If inheritance is possible, do the base class and subclasses go in separate files? Do I only have to attach the relevant subclass file to a particular game object, or the base class file as well?

Finally, is inheritance possible in both C# and UnityScript?

Subclassing (inheritance) is available in the Unity flavor of JavaScript as well as in C#. See MSDN for how to use inheritance in C#. To have an inheritance chain in JavaScript:

  1. Create a new JavaScript
  2. Put in this code:

    class MyCoolObject extends MonoBehaviour {
        var myCoolInt : int;
        var myCoolFloat : float
    }
    
    
  3. Now you have a new class that implements all the methods of MonoBehaviour(such as Update() and FixedUpdate()). If you want to create a subclass of MyCoolObject, just:

    class MyCoolerObject extends MyCoolObject {
        var myCoolerInt : int;
        var myCoolerFloat : float;
    }
    
    
  4. Now if you reference MyCoolerObject in a script, both the cooler variables and the cool variables will show up in the inspector.

Unity does support subclassing, but it does NOT support dynamic dispatch for "Unity" method calls.

For example:

public class MyBehaviour : MonoBehaviour
{
    private void Start()
    {
        Debug.Log("MyBehaviour created");
    }
}

public class DerivedBehaviour : MyBehaviour
{

}

If you attach a `DerivedBehaviour` script to a GameObject, it will NOT call MyBehaviour.Start() on startup. If you want to do that then you have to do it manually:

public class MyBehaviour : MonoBehaviour
{
    private virtual void Start()
    {
        Debug.Log("MyBehaviour created");
    }
}

public class DerivedBehaviour : MyBehaviour
{
    private virtual void Start()
    {
        base.Start();
    }
}

Note that making the methods virtual in the first example would not fix the problem.

This applies to all "Unity" calls (e.g. Awake, Start, Update, LateUpdate, OnLevelLoaded etc.). "Normal" method calls work correctly like you would expect in any .NET app.

Every script that you add to an object is itself a subclass of MonoBehavior, and from then on it's .Net all the way down (or up, actually). Here are two examples:

  1. As a really straightforward example, you could take a look at the code for Rock'n'Roll dice. As you can see, there's a DieController MonoBehavior, which contains most of the general code, and then there are some subclasses for the various types of die, which override a few relevant properties.

  2. You could also take a look at the behaviors included in UnitySteer, some of which inherit from a very basic VehicleBehavior and also implement particular interfaces.

In short, any language feature that would apply to a regular .Net class applies to your Unity scripts as well, since they are simply .Net classes.

I just wanted to add that when using Inheritance for MonoBehaviour objects, the GetComponent() function on the GameObject class will return derived objects as well. This wasn't immediately obvious to me, but is very useful for deriving MonoBehaviours to share functionality and write abstract code in Unity.

Using your scenario, here's a very simple example:

public class CharacterBehaviour : MonoBehaviour
{
    void Start()
    {
        CharacterBehaviour behaviour = gameObject.GetComponent<CharacterBehaviour>();

        print("Behaviour Type: " + behaviour.GetType().Name);
    }
}

public class PlayerCharacterBehaviour : CharacterBehaviour
{

}

public class AICharacterBehaviour : CharacterBehaviour
{

}

With a GameObject that has a PlayerCharacterBehaviour attached, you will see:

Behaviour Type: PlayerCharacterBehaviour

With a GameObject that has an AICharacterBehaviour attached, you will see:

Behaviour Type: AICharacterBehaviour

This lets you write generic code against all objects with a CharacterBehaviour attached.

Inheriting from GameObject seems to crash unity. It would be nice to do to make it easier to interface with other code.

try this:

public class first : MonoBehaviour {

        // Use this for initialization
        void Start () {
           GameObject go = new GameObject("Child");
           go.AddComponent<ChildClass>();
        }

        // Update is called once per frame
        void Update () {

        }
    }


    public class ChildClass : first
    {
        void Start()
        {
           print("Hello from child");
        }
    }

From the original question: do the base class and subclasses go in separate files?

was not answered yet...

I believe the answer is "yes" in JavaScript and optional in C# is that correct?

I wish that was not the case since a proliferation of files is not so easy to manage.

Check out this useful tutorial from Unity! Unity Connect

For anybody in 2021 looking for the answer, Unity does not support sub classes

you can’t do

public class A
{
public class B : A
{
}
}

The answer ins’t right