// Copyright (c) Wojciech Figat. All rights reserved.
using System;
namespace FlaxEngine
{
///
/// Virtual input action binding. Helps with listening for a selected input event.
///
public class InputEvent : IComparable, IComparable
{
///
/// The name of the action to use. See .
///
[Tooltip("The name of the action to use.")]
public string Name;
///
/// Returns true if the event has been triggered during the current frame (e.g. user pressed a key). Use to catch events without active waiting.
///
public bool Active => Input.GetAction(Name);
///
/// Returns the event state. Use , , to catch events without active waiting.
///
public InputActionState State => Input.GetActionState(Name);
///
/// Occurs when event is triggered (e.g. user pressed a key). Called before scripts update.
///
[System.Obsolete("Use Pressed instead")]
public event Action Triggered;
///
/// Occurs when event is pressed (e.g. user pressed a key). Called before scripts update.
///
public event Action Pressed;
///
/// Occurs when event is being pressing (e.g. user pressing a key). Called before scripts update.
///
public event Action Pressing;
///
/// Occurs when event is released (e.g. user releases a key). Called before scripts update.
///
public event Action Released;
///
/// Initializes a new instance of the class.
///
public InputEvent()
{
Input.ActionTriggered += Handler;
}
///
/// Initializes a new instance of the class.
///
/// The action name.
public InputEvent(string name)
{
Input.ActionTriggered += Handler;
Name = name;
}
///
/// Finalizes an instance of the class.
///
~InputEvent()
{
Input.ActionTriggered -= Handler;
Triggered = null;
Pressed = null;
Pressing = null;
Released = null;
}
private void Handler(string name, InputActionState state)
{
if (!string.Equals(name, Name, StringComparison.OrdinalIgnoreCase))
return;
switch (state)
{
case InputActionState.None: break;
case InputActionState.Waiting: break;
case InputActionState.Pressing:
Pressing?.Invoke();
break;
case InputActionState.Press:
Triggered?.Invoke();
Pressed?.Invoke();
break;
case InputActionState.Release:
Released?.Invoke();
break;
default: break;
}
}
///
/// Releases this object.
///
public void Dispose()
{
Input.ActionTriggered -= Handler;
Triggered = null;
Pressed = null;
Pressing = null;
Released = null;
GC.SuppressFinalize(this);
}
///
public int CompareTo(InputEvent other)
{
return string.Compare(Name, other.Name, StringComparison.Ordinal);
}
///
public int CompareTo(object obj)
{
return obj is InputEvent other ? CompareTo(other) : -1;
}
///
public override int GetHashCode()
{
return Name?.GetHashCode() ?? 0;
}
///
public override bool Equals(object obj)
{
return obj is InputEvent other && string.Equals(Name, other.Name, StringComparison.Ordinal);
}
///
public override string ToString()
{
return Name;
}
}
}