MonoBehaviours

MonoBehaviours

MonoBehaviours is a class within the Unity API that is used to create components. Components are logic that you can attach to a game object. They have useful methods which are called by Unity itself such as Awake, Start, Update, OnTriggerEnter, OnTriggerExit, etc… You may find all those methods and the order in which they are called here: https://docs.unity3d.com/Manual/ExecutionOrder.html

Usually MonoBehaviours are used whenever you need logic that interacts with the game world such as “Character” or “MovingPlatform”. It is good practice to keep your MonoBehaviours simple and modular so that they can be reused in different circumstances.

Example of a MonoBehavior

/// <summary>
/// Billboard Allows you to make a game object look at the camera.
/// </summary>
public class Billboard : MonoBehaviour
{
    [Tooltip("Use the lookAt function or make the object face the same way as the camera?")]
    [SerializeField] protected bool m_LookAt;
    
    protected Transform m_CameraTransform;
    
    /// <summary>
    /// GEt the camera transform.
    /// </summary>
    private void Awake()
    {
        m_CameraTransform = Camera.main.transform;
    }

    /// <summary>
    /// Look at the camera.
    /// </summary>
    void Update() 
    {
        if (m_LookAt) {
            transform.LookAt(m_CameraTransform.position, Vector3.up);
        } else {
            transform.forward = m_CameraTransform.forward;
        }
    }
}