# Singletons

{% hint style="info" %}
All sub-pages in Singletons page listed in usage order priority.
{% endhint %}

## 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:**

```csharp
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:**

```csharp
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.

{% hint style="success" %}
Difference between simple and MonoSingleton classes:

* Inherit from MonoSingleton -> Instance can't be NULL, it always creates automaticaly
* If don't inherit and implement simple singleton -> instance can be NULL, you need to replace prefab in scene before access singleton or create it manualy with Instantiate() Unity function.
  {% endhint %}

{% hint style="warning" %}
Code conventions with singleton:

* If <mark style="color:red;">first letter in Instance is</mark>  <mark style="color:red;background-color:orange;">**I**</mark>  *high case* -> you can don't check for null because it will be automaticaly instantiated
* If <mark style="color:red;">first letter in instance is</mark>  <mark style="color:red;background-color:orange;">**i**</mark>  *lower case* -> you should check if it's null or keep in mind that it's possible, because singleton will not be created automaticaly
  {% endhint %}
