By default, every object in Unity is an extension of the MonoBehavior class. However, the majority of game objects have several common variables that have to be declared. For the sake of saving developer time, we should extend MonoBehavior to automatically include these variables  – that is the purpose of ExtendedMonoBehavior.

Common Variables

Typically, most game objects have a script that includes the following variables somewhere in the code:

  • A cached reference to the object’s Transform.
  • A cached reference to the gameObject
  • A boolean variable (default false) that checks whether the object’s initial setup functions are executed.
  • An integer containing the ID of the object.
  • A Vector3 for temporary vector actions.
  • A Transform for temporary transform references.

While not every game requires each object to have an ID, it is often times good to have one in the case multiple copies of an object appear as it allows the developer to access one specifically. The two temporary references just save a slight amount of time and code as it gives the developer a temporary Vector3 and Transform to utilize in scripts that just need a one-off reference.

ExtendedMonoBehavior.cs

using UnityEngine;
using System.Collections;

public class ExtendedMonoBehaviour : MonoBehaviour {
    // This class is used to add some common variables to MonoBehaviour, rather than
    // constantly repeating the same declarations in every class.
    
    public Transform myTransform;
    public GameObject myGameObject;
    
    public bool didInit;
    
    public int id;
    
    [System.NonSerialized]
    public Vector3 tempVector3;
    
    [System.NonSerialized]
    public Transform tempTransform;
    
    public virtual void SetID (int anID) {
        id= anID;
    }
}

Up Next: BaseStatsManager

Many games feature a player character or characters with certain attributes such as health, name, etc. The next script features an extensible class where the developer can create custom stats for each different player-controlled character.