UnityTimer icon indicating copy to clipboard operation
UnityTimer copied to clipboard

Manually initialize TimerManager

Open Petethegoat opened this issue 3 years ago • 0 comments

Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)
The following scene GameObjects were found:
TimerManager

If the first time a timer is registered is in the OnDisable or OnDestroy function, then it may create the TimerManager as a scene is closed (for example, when exiting playmode)

I simply added a method to initialize it manually. This could also use RuntimeInitializeOnLoadMethod and occur with no user action required.

    /// <summary>
    /// Initializes the TimerManager, useful if your first Timer usage
    /// may otherwise be in OnDisable or OnDestroy, which may be called when exiting playmode.
    /// </summary>
    public static void InitializeManager()
	{
        if(Timer._manager == null)
        {
            TimerManager managerInScene = Object.FindObjectOfType<TimerManager>();
            if(managerInScene != null)
            {
                Timer._manager = managerInScene;
            }
            else
            {
                GameObject managerObject = new GameObject { name = "TimerManager" };
                Timer._manager = managerObject.AddComponent<TimerManager>();
                GameObject.DontDestroyOnLoad(managerObject);
            }
        }
    }

Petethegoat avatar Feb 23 '22 21:02 Petethegoat