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

111 lines
3.3 KiB
C#

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using System.Linq;
namespace BITKit
{
[System.Serializable]
public class InputActionGroup : IDisposable
{
private int lockFile = Guid.NewGuid().GetHashCode();
public bool allowGlobalActivation = true;
[SerializeField, ReadOnly] private bool isEnabled;
private InitializationState state = InitializationState.None;
public ValidHandle allowInput = new();
private readonly ConcurrentDictionary<string,InputAction> actions = new();
public InputActionGroup RegisterCallback(InputActionReference reference,
Action<InputAction.CallbackContext> callback)
{
if (reference is null)
{
Debug.LogWarning($"未知的引用");
return this;
}
EnsureConfiguration();
var action = actions.GetOrAdd(reference.name, _ =>
{
var newAction = reference.action.Clone();
newAction.Rename(reference.name);
return newAction;
});
action.RegisterCallback(callback);
allowInput.Invoke();
return this;
}
public void Inherit(InputActionGroup other)
{
throw new NotImplementedException();
}
public InputAction GetAction(string name)
{
if(actions.TryGetValue(name,out var action))
return action;
throw new ArgumentException($"未知的引用{name}");
}
public InputAction GetAction(InputActionReference reference)
{
if(actions.TryGetValue(reference.name,out var action))
return action;
throw new ArgumentException($"未知的引用{reference.name}");
}
public void UnRegisterCallback(InputActionReference reference, Action<InputAction.CallbackContext> callback)
{
if(actions.TryGetValue(reference.name,out var action))
action.UnRegisterCallback(callback);
}
private void EnsureConfiguration()
{
if (state is not InitializationState.Initialized)
{
Init();
state = InitializationState.Initialized;
}
}
private void Init()
{
if (allowGlobalActivation)
BITInputSystem.AllowInput.AddListener(ListenGlobalInput);
allowInput.AddListener(AllowInput);
}
private void ListenGlobalInput(bool allowInput)
{
this.allowInput.SetDisableElements(lockFile, !allowInput);
}
private void AllowInput(bool allow)
{
foreach (var action in actions.Values)
{
if (allow)
{
action.Enable();
}
else
{
action.Disable();
}
}
isEnabled = allow;
}
public void Dispose()
{
foreach (var action in actions.Values)
{
action.Disable();
action.Dispose();
}
actions.Clear();
}
}
}