Movement/VariableMovement/VariableMovementWithState.cs

81 lines
2.2 KiB
C#

using System;
using UnityEngine.InputSystem;
namespace Syntriax.Modules.Movement.VariableMovement
{
public class VariableMovementWithState : IVariableMovementWithState
{
public Action<bool> OnToggleStateChanged { get; set; } = null;
private bool _enabled = false;
public bool Enabled
{
get => _enabled;
set
{
bool isNewValue = _enabled != value;
_enabled = value;
if (isNewValue)
OnToggleStateChanged.Invoke(value);
}
}
private VMAsset _asset;
public VMAsset Asset
{
get => _asset;
set
{
UpdateBindings();
_asset = value;
Enabled = false;
}
}
private IInputActionCollection _inputCollection = null;
public IInputActionCollection InputCollection
{
set
{
if (_inputCollection == value)
return;
_inputCollection = value;
UpdateBindings();
}
}
protected InputAction actionReference = null;
public VariableMovementWithState(VMAsset asset, IInputActionCollection inputCollection)
{
InputCollection = inputCollection;
Asset = asset;
}
protected void Cancelled(InputAction.CallbackContext obj) => Enabled = false;
protected void Performed(InputAction.CallbackContext obj) => Enabled = true;
protected void UpdateBindings()
{
if (actionReference != null)
{
actionReference.performed -= Performed;
actionReference.canceled -= Cancelled;
}
if (_inputCollection != null)
foreach (InputAction action in _inputCollection)
if (action.name == Asset.ActionReference)
{
actionReference = action;
actionReference.performed += Performed;
actionReference.canceled += Cancelled;
break;
}
}
}
}