MonoSingleton
Introduction
MonoSingleton is an inheritable MonoBehaviour. It is used to create static managers. MonoSingletons is DontDestroyOnLoad (not destroyed on scene destroy).
Example
An useless manager
using UnityEngine;
using Wonderland;
public class MonoSingletonTest : MonoSingleton<MonoSingletonTest> {
public int UnityTime = 0;
void Update() {
UnityTime = Mathf.RoundToInt(Time.time);
}
}
A call in another script
// with test (or without if you sure instance exists)
int getMyTime() {
if (MonoSingletonTest.Instance != null) {
return MonoSingletonTest.Instance.UnityTime;
}
return 0;
}
// or with dynamic
int getMyTime() {
try {
return MonoSingletonTest.TryInstance.UnityTime;
} catch {}
return 0;
}
// or wait dynamic
async int getMyTime() {
try {
return (await MonoSingletonTest.WaitInstance()).UnityTime;
} catch {}
return 0;
}
// in Start
async void Start() {
await GameManager.WaitInstance();
// ... do something
// this is easy but can lock your game (and the editor) if you fail your initialization procedure.
}
For a global game manager, set NeverReplace value to true. If you set the manager in many scenes, it will ignored and the game continue to use your first instanciated manager.
protected override bool NeverReplace => true;