using System; using System.Collections.Generic; using UnityEngine.InputSystem; namespace DanieleMarotta.RiversongCodeShowcase { [Service(typeof(ICancelAction))] [GameSystemGroup(typeof(LateGameSystemGroup))] public class CancelActionSystem : GameSystem, IUpdatable, ICancelAction { private readonly List<(int, Func)> _handlers = new(); private Comparison<(int, Func)> _handlerComparison; public CancelActionSystem(IServiceLocator serviceLocator) : base(serviceLocator) { } public void Update() { if (!TryGetCancelActionType(out var cancelActionType)) return; foreach (var (_, handler) in _handlers) if (handler.Invoke(cancelActionType)) return; } public void AddHandler(int priority, Func cancelAction) { _handlerComparison ??= (handler, otherHandler) => { var (handlerPriority, _) = handler; var (otherHandlerPriority, _) = otherHandler; return otherHandlerPriority.CompareTo(handlerPriority); }; _handlers.Add((priority, cancelAction)); _handlers.Sort(_handlerComparison); } private static bool TryGetCancelActionType(out CancelActionType cancelActionType) { if (Keyboard.current.escapeKey.wasPressedThisFrame) { cancelActionType = CancelActionType.EscapeKey; return true; } if (Mouse.current.rightButton.wasPressedThisFrame) { cancelActionType = CancelActionType.RightMouseButton; return true; } cancelActionType = CancelActionType.None; return false; } } }