perf!: events refactored throughout all the project to use Event<> class

All delegate events are refactored to use the Event<TSender> and Event<TSender, TArgument> for performance issues regarding delegate events creating garbage, also this gives us better control on event invocation since C# Delegates did also create unnecessary garbage during Delegate.DynamicInvoke
This commit is contained in:
2025-05-31 00:14:43 +03:00
parent 996e61d0ad
commit 61e2761580
58 changed files with 637 additions and 485 deletions

View File

@@ -5,9 +5,17 @@ namespace Syntriax.Engine.Systems.StateMachine;
public class StateMachine : Behaviour
{
public event StateChangedEventHandler? OnStateChanged = null;
public Event<StateMachine, StateChangedArguments> OnStateChanged { get; } = new();
private readonly Event<IState, IState.StateTransitionReadyArguments>.EventHandler delegateOnStateTransitionReady = null!;
private IState _state = new State();
public StateMachine()
{
delegateOnStateTransitionReady = OnStateTransitionReady;
}
[Serialize]
public IState State
{
@@ -18,20 +26,20 @@ public class StateMachine : Behaviour
return;
IState previousState = _state;
previousState.OnStateTransitionReady -= OnStateTransitionReady;
previousState.OnStateTransitionReady.RemoveListener(delegateOnStateTransitionReady);
_state = value;
previousState.TransitionFrom(value);
value.TransitionTo(_state);
OnStateChanged?.Invoke(this, previousState, value);
OnStateChanged?.Invoke(this, new(value, previousState));
value.OnStateTransitionReady += OnStateTransitionReady;
value.OnStateTransitionReady.AddListener(delegateOnStateTransitionReady);
}
}
private void OnStateTransitionReady(IState sender, IState toState)
private void OnStateTransitionReady(IState sender, IState.StateTransitionReadyArguments args)
{
State = toState;
State = args.ToState;
while (State.GetNextState() is IState nextState)
State = nextState;
}
@@ -47,5 +55,5 @@ public class StateMachine : Behaviour
State.Update();
}
public delegate void StateChangedEventHandler(StateMachine sender, IState previousState, IState newState);
public readonly record struct StateChangedArguments(IState CurrentState, IState PreviousState);
}