What is MonoBehaviour in Unity 3D?

MonoBehaviour is the base class from which every Unity script derives. It offers some life cycle functions that are easier for you to develop your app and game. A picture is worthy of thousands of words.

Source of the image: https://docs.unity3d.com/uploads/Main/monobehaviour_flowchart.svg

enter image description here


While the following statement is correct,

  • "MonoBehaviour is the base class from which every Unity script derives" -

I honestly feel it can be misleading to beginners. The phrase - "every Unity script" - being the culprit.

It gives a beginner the notion that all scripts created in unity must extend Monobehaviour. Which is not the case. You can create scripts that house classes that extend the c# base object class. In doing so, your script is then categorised as not a Unity script but nothing stops it from interacting with other Unity scripts and vice versa.


MonoBehaviour is another class that VariablesAndFunctions is inheriting from. This allows the inheritor to use the methods and variables of the other class providing they have the correct access level modifier set.

In the below example Class1 inherits from Base and so can use the protected method Method1

public class Base
{
    protected void Method1 { /*...*/ }
}

public class Class1 : Base
{
    public void Method2 { Method1(); }
}

Note in this particular example it would be better for Method1 to be marked as abstract or virtual so then Class1 can override it like so:

protected override Method1()
{
    //...

    base.Method1(); //Call the implementation of Method1 in Base here

    //...
}

In particular though MonoBehaviour is described as being:

MonoBehaviour is the base class from which every Unity script derives.

Therefore when doing scripting in unity, you use this base class to better control how things are accessed so you do not need to do it yourself.

Tags:

C#

Unity3D