Skip to content

Singleton

Matheus Lessa Rodrigues edited this page Oct 28, 2017 · 1 revision

Singleton

The Singleton design pattern. Ever wanted to access a MonoBehaviour from anywhere in the code? With this pattern, you will be able to MyScript.Instance.someField.

Note

Beware, though, as it's generally accepted that using lots of Singletons is a code smell. What it does is that it introduces a hard dependency between scripts and makes it hard to refactor later. As a reasonable rule of thumb, only use it as a last resort or when prototyping.

Example

using UnityEngine;
using BitStrap;

public sealed class MyScript : Singleton<MyScript>
{
    public int someField;
}

// From another script
public sealed class SomeRegularScript : MonoBehaviour
{
    private void Start()
    {
        Debug.Log( "Some global value {0}", MyScript.Instance.someField );
    }
}
Clone this wiki locally