I have a singleton GameManager() whose Awake() function is called twice: the first time when the object awakes, the second time when another object uses the singleton for the first time.
This is the Singleton (from: A modern singleton in Unity | Martin Zikmund):
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static readonly Lazy<T> LazyInstance = new Lazy<T>(CreateSingleton);
public static T Instance => LazyInstance.Value;
private static T CreateSingleton()
{
var ownerObject = new GameObject($"{typeof(T).Name} (singleton)");
var instance = ownerObject.AddComponent<T>();
DontDestroyOnLoad(ownerObject);
return instance;
}
}
This is the GameManager:
public class GameManager : Singleton<GameManager>
{
public void Awake() {
Debug.Log("GameManager awake");
}
public void Start() {
Debug.Log("GameManager started");
}
public void isEmulator() { return true; }
}
This is one of the gameobjects that uses it first:
public class ControllerManager : MonoBehaviour
{
private bool isEmulator = false;
void Start()
{
Debug.Log("ControllerManager Started");
isEmulator = GameManager.Instance.isEmulator();
}
}
And this is what happens when I run it (in the editor):
- I checked and I’m sure GameManager is not assigned elsewhere nor I’m using the script twice on the same object
- ControllerManager() uses the GameManager in its Start().
I’m quite lost at this point. What is the obvious mistake I’m making that I’m not seeing?
Thank you in advance
