CodeBlanks Logo Icon CodeBlanks

What is MonoBehaviour?

Learn the MonoBehaviour base class and its role.

What is MonoBehaviour?

MonoBehaviour is the base class inside UnityEngine. To add a C# script to a GameObject as a component, your class must derive from it. This way Unity binds your script to an object in the scene.

using UnityEngine;

public class Oyuncu : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Merhaba");
    }
}

The class above can now be added to a GameObject as a component.

Base class and lifecycle

MonoBehaviour is a base class; with : MonoBehaviour you derive from it. Unity itself calls certain methods of this class without you calling them, and this is called the lifecycle. You only write the methods; Unity manages the call order.

public class Dusman : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Hazir");
    }

    void Update()
    {
        // runs every frame
    }
}

It is enough to spell the method names correctly.

Practice Write your first MonoBehaviour

Derive a class named Oyuncu from MonoBehaviour. In a Start method, print the text "Merhaba Unity" with Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class Oyuncu : MonoBehaviour
{
    // Start metodunu ve yazdirma kodunu buraya ekle
}

Sample solution

Player.cs
using UnityEngine;

public class Oyuncu : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Merhaba Unity");
    }
}

Expected output

Merhaba Unity

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How must a class be defined so that a script can be added to a GameObject as a component?

  • As class Oyuncu : MonoBehaviour Correct answer
  • As class Oyuncu : GameObject
  • As static class Oyuncu
  • As class Oyuncu with no base class

Explanation: Classes that derive from MonoBehaviour gain Unity's lifecycle methods and can be added as components.

2 Derive the class from MonoBehaviour

Question
using UnityEngine;

public class Oyuncu : ____
{
    void Start()
    {
        Debug.Log("Hazir");
    }
}
Answer
using UnityEngine;

public class Oyuncu : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Hazir");
    }
}

Explanation: Script classes derive from the MonoBehaviour base class; otherwise Unity does not accept them as components.

3 Parts of MonoBehaviour

Term Meaning
MonoBehaviour The base class scripts derive from
: MonoBehaviour The inheritance declaration
void Start() A method Unity calls
Debug.Log Writes text to the console

All lessons in Beginner