From f0fd50061f044d1bcc11d849e8fdcf7224c97d73 Mon Sep 17 00:00:00 2001 From: Inspiaaa Date: Fri, 6 Sep 2024 23:38:11 +0200 Subject: [PATCH] Add scene-local CoroutineManager feature --- src/CoroutineManager.cs | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/CoroutineManager.cs b/src/CoroutineManager.cs index da8851c..aee1535 100644 --- a/src/CoroutineManager.cs +++ b/src/CoroutineManager.cs @@ -8,6 +8,7 @@ namespace HCoroutines; public partial class CoroutineManager : Node { public static CoroutineManager Instance { get; private set; } + private static CoroutineManager globalInstance; public float DeltaTime { get; private set; } public double DeltaTimeDouble { get; private set; } @@ -21,6 +22,34 @@ public partial class CoroutineManager : Node private DeferredHashSet activePhysicsProcessCoroutines = new(); private HashSet aliveRootCoroutines = new(); + public override void _EnterTree() + { + Instance = this; + ProcessMode = ProcessModeEnum.Always; + IsPaused = GetTree().Paused; + + if (IsAutoloaded()) + { + // This instance is the global (autoloaded) instance that is shared between scenes. + globalInstance = this; + } + } + + public override void _ExitTree() + { + if (Instance == this) + { + // Switch back to the global (autoloaded) manager when the scene-local instance is removed (e.g. when + // the current scene is changed). + Instance = globalInstance; + } + } + + private bool IsAutoloaded() + { + return GetParent() == GetTree().Root && GetTree().CurrentScene != this; + } + /// /// Starts and initializes the given coroutine. /// @@ -56,13 +85,6 @@ private DeferredHashSet GetUpdatePoolOfCoroutine(CoroutineBase co }; } - public override void _EnterTree() - { - Instance = this; - ProcessMode = ProcessModeEnum.Always; - IsPaused = GetTree().Paused; - } - public override void _Process(double delta) { DeltaTime = (float)delta;