1️⃣Singletons

Fundamental section of init project which describes main singleton scripts

All sub-pages in Singletons page listed in usage order priority.

How to create singleton

If you want to create singleton, you can use inherit from MonoSingleton.cs, but keep in mind that

if Instance of MonoSignleton is null -> Instance will be created with default class values.

Here is MonoSingleton example:

public class TimeManager : MonoSingleton<TimeManager>
{
    private float defaultTimeScale;
    private float defaultFixedDeltaTime;

    protected override void Awake() {
        // this is important because MonoSingleton.Awake() will init our object
        base.Awake();
        
        // note that here will double check if awakeDestroyObj is true,
        // because if it is -> object that runs this script will be destroyed
        // and we dont need to run any init code below 
        // and dont need to call DontDestroyOnLoad
        if (awakeDestroyObj) {
            return;
        }
        DontDestroyOnLoad(gameObject);
        
        // all stuff on singleton created successfuly
        defaultTimeScale = Time.timeScale;
        defaultFixedDeltaTime = Time.fixedDeltaTime;
    }
}

Here is simple singleton that will not be created automaticaly if null and it's snippet:

public class _Class_Name_ : Monobehaviour {
    public static _Class_Name_ instance;
    
    private void Awake() {
        if (instance == null) {
            instance = this;
        }
        else {
            Destroy(gameObject);
            return;
        }
        
        // all stuff on singleton created successfuly
    }
}

if Instance of simple singleton is null -> it will not be created automaticaly and you can get null reference exception.

Last updated