Movement/VariableMovement/VariableMovementWithState.cs

82 lines
2.3 KiB
C#
Raw Normal View History

2022-03-09 21:46:49 +03:00
using UnityEngine.Events;
using UnityEngine.InputSystem;
namespace Syntriax.Modules.Movement.VariableMovement
{
public class VariableMovementWithState : IVariableMovementWithState
{
public UnityEvent<bool> OnToggleStateChanged { get; protected 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();
2022-03-09 21:46:49 +03:00
_asset = value;
Enabled = false;
}
}
private IInputActionCollection _inputCollection = null;
public IInputActionCollection InputCollection
{
set
{
if (_inputCollection == value)
return;
_inputCollection = value;
UpdateBindings();
}
}
2022-03-09 21:46:49 +03:00
protected InputAction actionReference = null;
public VariableMovementWithState(VMAsset asset, IInputActionCollection inputCollection)
2022-03-09 21:46:49 +03:00
{
InputCollection = inputCollection;
2022-03-09 21:46:49 +03:00
OnToggleStateChanged = new UnityEvent<bool>();
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)
2022-06-10 11:16:19 +03:00
if (action.name == Asset.ActionReference)
{
actionReference = action;
actionReference.performed += Performed;
actionReference.canceled += Cancelled;
break;
}
}
2022-03-09 21:46:49 +03:00
}
}