BITFALL/Assets/BITKit/Unity/Scripts/InputSystem/InputActionGroup.cs

97 lines
2.6 KiB
C#
Raw Normal View History

2023-06-08 14:09:50 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using System.Linq;
2023-09-01 14:33:54 +08:00
2023-06-08 14:09:50 +08:00
namespace BITKit
{
[System.Serializable]
public class InputActionGroup : IDisposable
{
2023-09-01 14:33:54 +08:00
private int lockFile = Guid.NewGuid().GetHashCode();
2023-06-08 14:09:50 +08:00
public bool allowGlobalActivation = true;
2023-09-01 14:33:54 +08:00
[SerializeField, ReadOnly] private bool isEnabled;
private InitializationState state = InitializationState.None;
2023-06-08 14:09:50 +08:00
public ValidHandle allowInput = new();
2023-09-01 14:33:54 +08:00
private readonly List<InputAction> actions = new();
public InputActionGroup RegisterCallback(InputActionReference reference,
Action<InputAction.CallbackContext> callback)
2023-06-08 14:09:50 +08:00
{
if (reference is null)
{
Debug.LogWarning($"未知的引用");
return this;
}
2023-09-01 14:33:54 +08:00
2023-06-08 14:09:50 +08:00
EnsureConfiguration();
var action = reference.action.Clone();
actions
2023-09-01 14:33:54 +08:00
.Where(x => x.name == action.name)
.CreateOrAddIfEmety(actions, action)
.ForEach(x => { x.RegisterCallback(callback); });
2023-06-08 14:09:50 +08:00
return this;
}
2023-09-01 14:33:54 +08:00
2023-06-08 14:09:50 +08:00
public void UnRegisterCallback(InputActionReference reference, Action<InputAction.CallbackContext> callback)
{
foreach (var action in actions.Where(x => x.name == reference.action.name))
{
action.UnRegisterCallback(callback);
}
}
2023-09-01 14:33:54 +08:00
private void EnsureConfiguration()
2023-06-08 14:09:50 +08:00
{
if (state is not InitializationState.Initialized)
{
Init();
state = InitializationState.Initialized;
}
}
2023-09-01 14:33:54 +08:00
private void Init()
2023-06-08 14:09:50 +08:00
{
if (allowGlobalActivation)
BITInputSystem.AllowInput.AddListener(Listen);
allowInput.AddListener(Allow);
}
2023-09-01 14:33:54 +08:00
private void Listen(bool allowInput)
2023-06-08 14:09:50 +08:00
{
this.allowInput.SetElements(lockFile, allowInput);
this.allowInput.SetDisableElements(lockFile, !allowInput);
}
2023-09-01 14:33:54 +08:00
private void Allow(bool allow)
2023-06-08 14:09:50 +08:00
{
foreach (var action in actions)
{
if (allow)
{
action.Enable();
}
else
{
action.Disable();
}
}
2023-09-01 14:33:54 +08:00
2023-06-08 14:09:50 +08:00
isEnabled = allow;
}
public void Dispose()
{
foreach (var action in actions)
{
action.Disable();
}
2023-09-01 14:33:54 +08:00
2023-06-08 14:09:50 +08:00
actions.Clear();
}
}
}