1οΈβ£Singletons
Fundamental section of init project which describes main singleton scripts
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.
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.
Code conventions with singleton:
If first letter in Instance is I high case -> you can don't check for null because it will be automaticaly instantiated
If first letter in instance is i lower case -> you should check if it's null or keep in mind that it's possible, because singleton will not be created automaticaly
Last updated