Inherit from a behaviour (JS)

How do I create a base behaviour which other behaviour could inherit from?

Example:

 // BasicBehaviour.js
 private var parentEntity_: Entity;

 function Awake() 
 {
    parentEntity_ = GetComponent(Entity);   
 }

I wish to have other MonoBehaviours inheriting from BasicBehaviour.js. How can this be accomplished?

In Javascript, your base behaviour as you've written it should be fine. It can act as a base class as it is. Because you haven't explicitly declared a class body, Unity's Javascript compiler automatically adds it, and makes your script inherit from MonoBehaviour.

However to create a new class which extends your BasicBehaviour class, you need to explicitly declare the class body (otherwise it automatically inherits from MonoBehaviour), and specify that it should extend BasicBehaviour.

So, given that you have BasicBehaviour.js which has no class body defined, you can create a class which inherits from it like this:

// --- ExtendedBehaviour.js ---
class ExtendedBehaviour extends BasicBehaviour {

    // variable declarations inside the class body, here
    var myVar : int = 10;

    // and functions go inside the class body too
    function Start() 
    {
        Debug.Log("Extended Start");
    }
}

One last thing, It's important to note that when dealing with scripts which inherit from MonoBehaviour (either directly, or indirectly), each class declaration needs to be in its own separate .js file, and the file must be named exactly the same as the class definition. (this of course happens automatically when you don't define the class body yourself).

This code is going to be in C#, since I don't know JavaScript.


public class BaseThing : MonoBehaviour
{
     // Class Code
}

// Then, in another file

public class SomeThing : BaseThing
{
     void Start() 
     {
          print("I am a MonoBehaviour class.");
     }
}

Derive your base class from MonoBehaviour, and derive other classes from your base class.