From 76ad60fad3bd8825bd20f77838f25def43fa31ea Mon Sep 17 00:00:00 2001 From: Syntriax Date: Fri, 30 May 2025 20:55:09 +0300 Subject: [PATCH] perf: tween pooling --- Engine.Systems/Tween/Tween.cs | 9 +++++++++ Engine.Systems/Tween/TweenManager.cs | 22 +++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Engine.Systems/Tween/Tween.cs b/Engine.Systems/Tween/Tween.cs index 91f912c..ab86045 100644 --- a/Engine.Systems/Tween/Tween.cs +++ b/Engine.Systems/Tween/Tween.cs @@ -69,6 +69,15 @@ internal class Tween : ITween internal void Reset() { + OnStarted.Clear(); + OnPaused.Clear(); + OnResumed.Clear(); + OnCancelled.Clear(); + OnCompleted.Clear(); + OnEnded.Clear(); + OnUpdated.Clear(); + OnDeltaUpdated.Clear(); + _counter = 0f; Progress = 0f; State = TweenState.Idle; diff --git a/Engine.Systems/Tween/TweenManager.cs b/Engine.Systems/Tween/TweenManager.cs index 856efdd..3a4b208 100644 --- a/Engine.Systems/Tween/TweenManager.cs +++ b/Engine.Systems/Tween/TweenManager.cs @@ -8,17 +8,36 @@ namespace Syntriax.Engine.Systems.Tween; public class TweenManager : UniverseObject, ITweenManager { private CoroutineManager coroutineManager = null!; + private readonly Queue queue = new(); private readonly Dictionary runningCoroutines = []; public ITween StartTween(float duration, ITweenManager.TweenSetCallback? setCallback = null) { - Tween tween = new(duration); + Tween tween = Get(duration); tween.OnUpdated.AddListener(tween => setCallback?.Invoke(tween.Value)); runningCoroutines.Add(tween, coroutineManager.StartCoroutine(RunTween(tween))); return tween; } + private Tween Get(float duration) + { + if (!queue.TryDequeue(out Tween? result)) + result = new(duration); + + result.Duration = duration; + return result; + } + + private void Return(Tween tween) + { + if (queue.Contains(tween)) + return; + + tween.Reset(); + queue.Enqueue(tween); + } + private IEnumerator RunTween(Tween tween) { tween.State = TweenState.Playing; @@ -40,6 +59,7 @@ public class TweenManager : UniverseObject, ITweenManager } runningCoroutines.Remove(tween); + Return(tween); } public void CancelTween(ITween tween)