From 9d96e6d5e58c171b5adf19832a3f7519fa796be1 Mon Sep 17 00:00:00 2001 From: Adam Graham Date: Tue, 15 Jun 2021 16:54:21 -0500 Subject: [PATCH] Kill tweens on scene unload --- Runtime/TweenManager.cs | 28 +++++++++++++++++++++++----- Runtime/Tweening.cs | 5 +++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/Runtime/TweenManager.cs b/Runtime/TweenManager.cs index 7b63bf5..7251e99 100644 --- a/Runtime/TweenManager.cs +++ b/Runtime/TweenManager.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using UnityEngine; +using UnityEngine.SceneManagement; namespace Zigurous.Tweening { @@ -39,8 +40,7 @@ internal static TweenManager Instance GameObject singleton = new GameObject(); singleton.name = typeof(TweenManager).Name; singleton.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector; - - _instance = singleton.AddComponent(); + singleton.AddComponent(); DontDestroyOnLoad(singleton); } } @@ -54,9 +54,14 @@ private void Awake() { _isUnloading = false; - if (_instance == null) { + if (_instance == null) + { _instance = this; - } else { + + SceneManager.sceneUnloaded += SceneUnloaded; + } + else + { Destroy(this); } } @@ -65,8 +70,11 @@ private void OnDestroy() { _isUnloading = true; - if (_instance == this) { + if (_instance == this) + { _instance = null; + + SceneManager.sceneUnloaded -= SceneUnloaded; } foreach (Tween tween in this.tweens) { @@ -176,6 +184,16 @@ internal void Track(Tween tween) } } + /// + /// Kills all tweens when the active scene is unloaded. + /// + private void SceneUnloaded(Scene scene) + { + if (Tweening.killTweensOnSceneUnload) { + Tweening.KillAll(); + } + } + } } diff --git a/Runtime/Tweening.cs b/Runtime/Tweening.cs index cb9884e..3231a8c 100644 --- a/Runtime/Tweening.cs +++ b/Runtime/Tweening.cs @@ -43,6 +43,11 @@ public static class Tweening /// public static float overshoot = 1.70158f; + /// + /// Kills all tweens when the active scene is unloaded. + /// + public static bool killTweensOnSceneUnload = true; + /// /// The initial amount of tweens that memory is allocated for when the /// system starts. Additional memory will be allocated as needed.