perf: memory allocation improvements on ITween.Loop method

This commit is contained in:
2026-02-20 11:22:34 +03:00
parent 9f54f89f6d
commit 785fee9b6b

View File

@@ -4,23 +4,35 @@ namespace Engine.Systems.Tween;
public static class TweenExtensions public static class TweenExtensions
{ {
private static readonly System.Collections.Generic.Dictionary<ITween, int> loopDictionary = [];
public static ITween Loop(this ITween tween, int count) public static ITween Loop(this ITween tween, int count)
{ {
Tween tweenConcrete = (Tween)tween; if (!loopDictionary.TryAdd(tween, count))
int counter = count; throw new($"Tween already has a loop in progress.");
tweenConcrete.OnCompleted.AddListener(_ => tween.OnCompleted.AddListener(looperDelegate);
{ tween.OnEnded.AddListener(looperEndDelegate);
if (counter-- <= 0)
return;
tweenConcrete.Reset();
tweenConcrete.State = TweenState.Playing;
});
return tween; return tween;
} }
private static readonly Core.Event<ITween>.EventHandler looperEndDelegate = sender => loopDictionary.Remove(sender);
private static readonly Core.Event<ITween>.EventHandler looperDelegate = sender =>
{
int counter = loopDictionary[sender] = loopDictionary[sender] - 1;
if (counter <= 0)
{
loopDictionary.Remove(sender);
return;
}
Tween tweenConcrete = (Tween)sender;
tweenConcrete.Reset();
tweenConcrete.State = TweenState.Playing;
};
public static ITween LoopInfinitely(this ITween tween) public static ITween LoopInfinitely(this ITween tween)
{ {
tween.OnCompleted.AddListener(repeaterDelegate); tween.OnCompleted.AddListener(repeaterDelegate);