Singleton - TheModderWasReplaced/AgriCore GitHub Wiki
Singletons are a way to access a certain script from anywhere in the scene. This allows to avoid the need to have a reference to the same object by multiple objects. Here is the code for an example of a singleton:
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
/// <summary>
/// Unique instance of <typeparamref name="T"/>
/// </summary>
public static T Instance { get; private set; }
private void Awake()
{
if (Instance != null)
{
Debug.LogWarning($"Another instance of {GetType().Name} has been found.");
Destroy(gameObject);
return;
}
Instance = gameObject.GetComponent<T>();
if (!DestroyOnLoad)
DontDestroyOnLoad(gameObject);
OnAwake();
}
/// <summary>
/// Defines if the singleton should be destroyed when loading a new scene
/// </summary>
protected virtual bool DestroyOnLoad => false;
/// <summary>
/// Called when <see cref="Awake"/> is called
/// </summary>
protected virtual void OnAwake() { }
}
If you make another class inherit this class, you will be able to access the first instance of it anywhere. For example, if you had class Foo : Singleton<Foo>
, you could get the instance with Foo.Instance
.
If you want more information, check this.