BITKit/Packages/Runtime~/Unity/Scripts/InputSystem/InputActionGroup.cs

89 lines
2.5 KiB
C#
Raw Normal View History

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