MonoBehaviour extends Behaviour and Behaviour extends Component. I want to know why these classes are separated and semantic meanings of these classes. Are there any purpose to
Component:
Component
is a base class for both Behaviour
and MonoBehaviour
. It is a base class of any script that can be attached to a GameObject.
This is what almost every Unity build-in script derives from. This includes Collider
and Rigidbody
.
Behaviour:
The most important thing to know about Behaviour
is that anything that inherits from it can be enabled or disabled. Do not inherit your script from this if you don't want it to be enabled/disabled.
For example, Rigidbody
cannot be enabled/disabled. This is why it inherits from the Component
class instead of Behaviour
.
Behaviour
inherits from Component
.
MonoBehaviour:
The most important thing to note about MonoBehaviour
is that you need it when you have to use coroutines, Invoking, or any Unity callback functions such as physics OnCollisionEnter
function, Start
, OnEnable
, OnDisable
, etc.
MonoBehaviour
inherits from Behaviour
so that your scripts can be enabled/disabled.
Are there any purpose to separate these classes?
Yes, like the answer above, they are separated so that you can use different features by inheriting from the appropriate component.
You want coroutine, Invoke
, InvokeRepeating
and be able to enable/disable your script? Use inherits from MonoBehaviour
.
You want to be able to enable or disable your script but don't need coroutine, Invoke
, InvokeRepeating
? Use Behaviour
.
When you have a scripts that should never be enabled/disabled, that should inherit from Component
.
Note that Behaviour
and Component
are used by Unity for internal stuff. You should not try to inherit your script from these.
The main reason for separating these is to conserve memory and also make the code in each component easy to maintain. This is better than writing thousands of lines of codes for a feature that one rarely use. By separating them and when they are loaded into the memory they are actually being used and not wasting space in the memory.
And are there any classes extending Behaviour or Component directly?
Yes.
MonoBehaviour
inherits directly from Behaviour
which then
inherits from Component
.
Collider
inherits from Component
directly. Then non base colliders
such as BoxCollider
and SphereCollider
inherits from that Collider
.