Class InputAction
A named input signal that can flexibly decide which input data to tap.
Namespace: UnityEngine.InputSystem
Syntax
[Serializable]
public sealed class InputAction : ICloneable, IDisposable
Remarks
An input action is an abstraction over the source of input(s) it receives. They are most useful for representing input as "logical" concepts (e.g. "jump") rather than as "physical" inputs (e.g. "space bar on keyboard pressed").
In its most basic form, an action is simply an object along with a collection of bindings that trigger the action.
// A simple action can be created directly using `new`. If desired, a binding
// can be specified directly as part of construction.
var action = new InputAction(binding: "<Gamepad>/buttonSouth");
// Additional bindings can be added using `AddBinding`.
action.AddBinding("<Mouse>/leftButton");
Bindings use control path expressions to reference controls. See InputBinding for more details. There may be arbitrary many bindings targeting a single action. The list of bindings targeting an action can be obtained through bindings.
By itself an action does not do anything until it is enabled:
action.Enable();
Once enabled, the action will actively monitor all controls on devices present in the system (see devices) that match any of the binding paths associated with the action. If you want to restrict the set of bindings used at runtime or restrict the set of devices which controls are chosen from, you can do so using bindingMask or, if the action is part of an InputActionMap, by setting the devices property of the action map. The controls that an action uses can be queried using the controls property.
When input is received on controls bound to an action, the action will trigger callbacks
in response. These callbacks are started, performed, and
canceled. The callbacks are triggered as part of input system updates
(see Update()), i.e. they happen before the respective
MonoBehaviour.Update
or MonoBehaviour.FixedUpdate
methods
get executed (depending on which updateMode the system is
set to).
In what order and how those callbacks get triggered depends on both the type of the action as well as on the interactions (see IInputInteraction) present on the bindings of the action. The default behavior is that when a control is actuated (i.e. moving away from its resting position), started is called and then performed. Subsequently, whenever the a control further changes value to anything other than its default value, performed will be called again. Finally, when the control moves back to its default value (i.e. resting position), canceled is called.
To hook into the callbacks, there are several options available to you. The most obvious one is to hook directly into started, performed, and/or canceled. In these callbacks, you will receive a InputAction.CallbackContext with information about how the action got triggered. For example, you can use ReadValue<TValue>() to read the value from the binding that triggered or use interaction to find the interaction that is in progress.
action.started += context => Debug.Log($"{context.action} started");
action.performed += context => Debug.Log($"{context.action} performed");
action.canceled += context => Debug.Log($"{context.action} canceled");
Alternatively, you can use the actionTriggered callback for actions that are part of an action map or the global onActionChange callback to globally listen for action activity. To simply record action activity instead of responding to it directly, you can use InputActionTrace.
If you prefer to poll an action directly as part of your MonoBehaviour.Update
or MonoBehaviour.FixedUpdate
logic, you can do so using the triggered
and ReadValue<TValue>() methods.
protected void Update()
{
// For a button type action.
if (action.triggered)
/* ... */;
// For a value type action.
// (Vector2 is just an example; pick the value type that is the right
// one according to the bindings you have)
var v = action.ReadValue<Vector2>();
}
Note that actions are not generally frame-based. What this means is that an action will observe any value change on its connected controls, even if the control changes value multiple times in the same frame. In practice, this means that, for example, no button press will get missed.
Actions can be grouped into maps (see InputActionMap) which can in turn be grouped into assets (see InputActionAsset).
Please note that actions are a player-only feature. They are not supported in edit mode.
For more in-depth reading on actions, see the manual.
Constructors
InputAction()
Construct an unnamed, free-standing action that is not part of any map or asset and has no bindings. Bindings can be added with AddBinding(InputAction, String, String, String, String). The action type defaults to Value.
Declaration
public InputAction()
Remarks
The action will not have an associated InputActionMap and actionMap
will thus be null
. Use AddAction(InputActionMap, String, InputActionType, String, String, String, String, String) instead if
you want to add a new action to an action map.
The action will remain disabled after construction and thus not listen/react to input yet. Use Enable() to enable the action.
// Create an action with two bindings.
var action = new InputAction();
action.AddBinding("<Gamepad>/leftStick");
action.AddBinding("<Mouse>/delta");
action.performed += ctx => Debug.Log("Value: " + ctx.ReadValue<Vector2>());
action.Enable();
InputAction(String, InputActionType, String, String, String, String)
Construct a free-standing action that is not part of an InputActionMap.
Declaration
public InputAction(string name = null, InputActionType type = InputActionType.Value, string binding = null, string interactions = null, string processors = null, string expectedControlType = null)
Parameters
Type | Name | Description |
---|---|---|
String | name | Name of the action. If null or empty, the action will be unnamed. |
InputActionType | type | Type of action to create. Defaults to Value, i.e. an action that provides continuous values. |
String | binding | If not null or empty, a binding with the given path will be added to the action right away. The format of the string is the as for path. |
String | interactions | If |
String | processors | If |
String | expectedControlType | The optional expected control type for the action (i.e. expectedControlType). |
Remarks
The action will not have an associated InputActionMap and actionMap
will thus be null
. Use AddAction(InputActionMap, String, InputActionType, String, String, String, String, String) instead if
you want to add a new action to an action map.
The action will remain disabled after construction and thus not listen/react to input yet. Use Enable() to enable the action.
Additional bindings can be added with AddBinding(InputAction, String, String, String, String).
// Create a button action responding to the gamepad A button.
var action = new InputAction(type: InputActionType.Button, binding: "<Gamepad>/buttonSouth");
action.performed += ctx => Debug.Log("Pressed");
action.Enable();
Properties
actionMap
The map the action belongs to.
Declaration
public InputActionMap actionMap { get; }
Property Value
Type | Description |
---|---|
InputActionMap | InputActionMap that the action belongs to or null. |
Remarks
If the action is a loose action created in code, this will be null
.
var action1 = new InputAction(); // action1.actionMap will be null
var actionMap = new InputActionMap();
var action2 = actionMap.AddAction("action"); // action2.actionMap will point to actionMap
See Also
activeControl
The currently active control that is driving the action. Null while the action is in waiting (Waiting) or canceled (Canceled) state. Otherwise the control that last had activity on it which wasn't ignored.
Declaration
public InputControl activeControl { get; }
Property Value
Type | Description |
---|---|
InputControl |
Remarks
Note that the control's value does not necessarily correspond to the value of the action (ReadValue<TValue>()) as the control may be part of a composite.
See Also
bindingMask
An optional mask that determines which bindings of the action to enable and which to ignore.
Declaration
public InputBinding? bindingMask { get; set; }
Property Value
Type | Description |
---|---|
Nullable<InputBinding> | Optional mask that determines which bindings on the action to enable. |
Remarks
Binding masks can be applied at three different levels: for an entire asset through
bindingMask, for a specific map through bindingMask, and for single actions through this property.
By default, none of the masks will be set (i.e. they will be null
).
When an action is enabled, all the binding masks that apply to it are taken into account. Specifically, this means that any given binding on the action will be enabled only if it matches the mask applied to the asset, the mask applied to the map that contains the action, and the mask applied to the action itself. All the masks are individually optional.
Masks are matched against bindings using Matches(InputBinding).
Note that if you modify the masks applicable to an action while it is enabled, the action's controls will get updated immediately to respect the mask. To avoid repeated binding resolution, it is most efficient to apply binding masks before enabling actions.
Binding masks are non-destructive. All the bindings on the action are left in place. Setting a mask will not affect the value of the bindings property.
// Create a free-standing action with two bindings, one in the
// "Keyboard" group and one in the "Gamepad" group.
var action = new InputAction();
action.AddBinding("<Gamepad>/buttonSouth", groups: "Gamepad");
action.AddBinding("<Keyboard>/space", groups: "Keyboard");
// By default, all bindings will be enabled. This means if both
// a keyboard and gamepad (or several of them) is present, the action
// will respond to input from all of them.
action.Enable();
// With a binding mask we can restrict the action to just specific
// bindings. For example, to only enable the gamepad binding:
action.bindingMask = InputBinding.MaskByGroup("Gamepad");
// Note that we can mask by more than just by group. Masking by path
// or by action as well as a combination of these is also possible.
// We could, for example, mask for just a specific binding path:
action.bindingMask = new InputBinding()
{
// Select the keyboard binding based on its specific path.
path = "<Keyboard>/space"
};
See Also
bindings
The list of bindings associated with the action.
Declaration
public ReadOnlyArray<InputBinding> bindings { get; }
Property Value
Type | Description |
---|---|
ReadOnlyArray<InputBinding> | List of bindings for the action. |
Remarks
This list contains all bindings from bindings of the action's actionMap that reference the action through their action property.
Note that on the first call, the list may have to be extracted from the action map first which may require allocating GC memory. However, once initialized, no further GC allocation hits should occur. If the binding setup on the map is changed, re-initialization may be required.
See Also
controls
The set of controls to which the action's bindings resolve.
Declaration
public ReadOnlyArray<InputControl> controls { get; }
Property Value
Type | Description |
---|---|
ReadOnlyArray<InputControl> | Controls resolved from the action's bindings. |
Remarks
This property can be queried whether the action is enabled or not and will return the set of controls that match the action's bindings according to the current setup of binding masks (bindingMask) and device restrictions (devices).
Note that internally, controls are not stored on a per-action basis. This means that on the first read of this property, the list of controls for just the action may have to be extracted which in turn may allocate GC memory. After the first read, no further GC allocations should occur except if the set of controls is changed (e.g. by changing the binding mask or by adding/removing devices to/from the system).
If the property is queried when the action has not been enabled yet, the system will first resolve controls on the action (and for all actions in the map and/or the asset). See Binding Resolution in the manual for details.
enabled
Whether the action is currently enabled, i.e. responds to input, or not.
Declaration
public bool enabled { get; }
Property Value
Type | Description |
---|---|
Boolean | True if the action is currently enabled. |
Remarks
An action is enabled by either calling Enable() on it directly or by calling Enable() on the InputActionMap containing the action. When enabled, an action will listen for changes on the controls it is bound to and trigger callbacks such as started, performed, and canceled in response.
See Also
expectedControlType
Name of control layout expected for controls bound to this action.
Declaration
public string expectedControlType { get; set; }
Property Value
Type | Description |
---|---|
String |
Remarks
This is optional and is null by default.
Constraining an action to a particular control layout allows determine the value type and expected input behavior of an action without being reliant on any particular binding.
id
A stable, unique identifier for the action.
Declaration
public Guid id { get; }
Property Value
Type | Description |
---|---|
Guid | Unique ID of the action. |
Remarks
This can be used instead of the name to refer to the action. Doing so allows referring to the action such that renaming the action does not break references.
interactions
Interactions applied to every binding on the action.
Declaration
public string interactions { get; }
Property Value
Type | Description |
---|---|
String | Interactions added to all bindings on the action. |
Remarks
This property is equivalent to appending the same string to the interactions field of every binding that targets the action. It is thus simply a means of avoiding the need configure the same interaction the same way on every binding in case it uniformly applies to all of them.
var action = new InputAction(interactions: "press");
// Both of the following bindings will implicitly have a
// Press interaction applied to them.
action.AddBinding("<Gamepad>/buttonSouth");
action.AddBinding("<Joystick>/trigger");
See Also
name
Name of the action.
Declaration
public string name { get; }
Property Value
Type | Description |
---|---|
String | Plain-text name of the action. |
Remarks
Can be null for anonymous actions created in code.
If the action is part of an InputActionMap, it will have a name and the name will be unique in the map. The name is just the name of the action alone, not a "mapName/actionName" combination.
The name should not contain slashes or dots but can contain spaces and other punctuation.
An action can be renamed after creation using Rename(InputAction, String)..
See Also
phase
The current phase of the action.
Declaration
public InputActionPhase phase { get; }
Property Value
Type | Description |
---|---|
InputActionPhase |
Remarks
When listening for control input and when responding to control value changes, actions will go through several possible phases.
In general, when an action starts receiving input, it will go to Started
and when it stops receiving input, it will go to Canceled.
When Performed is used depends primarily on the type
of action. Value will trigger Performed
whenever the value of the control changes (including the first time; i.e. it will first
trigger Started and then Performed
right after) whereas Button will trigger Performed
as soon as the button press threshold (
Note that both interactions and the action type can affect the phases that an action goes through. PassThrough actions will only ever use Performed and not go to Started or Canceled (as pass-through actions do not follow the start-performed-canceled model in general). Also, interactions can choose their
While an action is disabled, its phase is Disabled.
processors
Processors applied to every binding on the action.
Declaration
public string processors { get; }
Property Value
Type | Description |
---|---|
String | Processors added to all bindings on the action. |
Remarks
This property is equivalent to appending the same string to the processors field of every binding that targets the action. It is thus simply a means of avoiding the need configure the same processor the same way on every binding in case it uniformly applies to all of them.
var action = new InputAction(processors: "scaleVector2(x=2, y=2)");
// Both of the following bindings will implicitly have a
// ScaleVector2Processor applied to them.
action.AddBinding("<Gamepad>/leftStick");
action.AddBinding("<Joystick>/stick");
See Also
triggered
Whether the action was triggered (i.e. had performed called) this frame.
Declaration
public bool triggered { get; }
Property Value
Type | Description |
---|---|
Boolean |
Remarks
Unlike ReadValue<TValue>(), which will reset when the action goes back to waiting state, this property will stay true for the duration of the current frame (i.e. until the next Update() runs) as long as the action was triggered at least once.
if (myControls.gameplay.fire.triggered)
Fire();
See Also
type
Behavior type of the action.
Declaration
public InputActionType type { get; }
Property Value
Type | Description |
---|---|
InputActionType | General behavior type of the action. |
Remarks
Determines how the action gets triggered in response to control value changes.
For details about how the action type affects an action, see InputActionType.
Methods
Clone()
Return an identical instance of the action.
Declaration
public InputAction Clone()
Returns
Type | Description |
---|---|
InputAction | An identical clone of the action |
Remarks
Note that if you clone an action that is part of an InputActionMap, you will not get a new action that is part of the same map. Instead, you will get a free-standing action not associated with any action map.
Also, note that the id of the action is not cloned. Instead, the clone will receive a new unique ID. Also, callbacks install on events such as started will not be copied over to the clone.
Disable()
Disable the action such that is stop listening/responding to input.
Declaration
public void Disable()
Remarks
If the action is already disabled, this method does nothing.
If the action is currently in progress, i.e. if phase is
Started, the action will be canceled as
part of being disabled. This means that you will see a call on canceled
from within the call to Disable()
.
See Also
Dispose()
Release internal state held on to by the action.
Declaration
public void Dispose()
Implements
Remarks
Once enabled, actions will allocate a block of state internally that they will hold on to until disposed of. For free-standing actions, that state is private to just the action. For actions that are part of InputActionMaps, the state is shared by all actions in the map and, if the map itself is part of an InputActionAsset, also by all the maps that are part of the asset.
Note that the internal state holds on to GC heap memory as well as memory from the unmanaged, C++ heap.
Enable()
Enable the action such that it actively listens for input and runs callbacks in response.
Declaration
public void Enable()
Remarks
If the action is already enabled, this method does nothing.
By default, actions start out disabled, i.e. with enabled being false. When enabled, two things happen.
First, if it hasn't already happened, an action will resolve all of its bindings to InputControls. This also happens if, since the action was last enabled, the setup of devices in the system has changed such that it may impact the action.
Second, for all the controls bound to an action, change monitors (see IInputStateChangeMonitor) will be added to the system. If any of the controls changes state in the future, the action will get notified and respond.
Value type actions will also perform an initial state
check in the input system update following the call to Enable. This means that if
any of the bound controls are already actuated and produce a non-default
value,
the action will immediately trigger in response.
Note that this method only enables a single action. This is also allowed for action that are part of an InputActionMap. To enable all actions in a map, call Enable().
The InputActionMap associated with an action (if any), will immediately toggle to being enabled (see enabled) as soon as the first action in the map is enabled and for as long as any action in the map is still enabled.
The first time an action is enabled, it will allocate a block of state internally that it will hold on to until disposed of. For free-standing actions, that state is private to just the action. For actions that are part of InputActionMaps, the state is shared by all actions in the map and, if the map itself is part of an InputActionAsset, also by all the maps that are part of the asset.
To dispose of the state, call Dispose().
var gamepad = InputSystem.AddDevice<Gamepad>();
var action = new InputAction(type: InputActionType.Value, binding: "<Gamepad>/leftTrigger");
action.performed = ctx => Debug.Log("Action triggered!");
// Perform some fake input on the gamepad. Note that the action
// will *NOT* get triggered as it is not enabled.
// NOTE: We use Update() here only for demonstration purposes. In most cases,
// it's not a good method to call directly as it basically injects artificial
// input frames into the player loop. Usually a recipe for breakage.
InputSystem.QueueStateEvent(gamepad, new GamepadState { leftTrigger = 0.5f });
InputSystem.Update();
action.Enable();
// Now, with the left trigger already being down and the action enabled, it will
// trigger in the next frame.
InputSystem.Update();
See Also
ReadValue<TValue>()
Read the current value of the action. This is the last value received on started, or performed. If the action is in canceled or waiting phase, returns default(TValue).
Declaration
public TValue ReadValue<TValue>()
where TValue : struct
Returns
Type | Description |
---|---|
TValue | The current value of the action or |
Type Parameters
Name | Description |
---|---|
TValue | Value type to read. Must match the value type of the binding/control that triggered. |
Remarks
This method can be used as an alternative to hooking into started, performed,
and/or canceled and reading out the value using ReadValue<TValue>()
there. Instead, this API acts more like a polling API that can be called, for example, as part of
MonoBehaviour.Update
.
// Let's say you have a MyControls.inputactions file with "Generate C# Class" enabled
// and it has an action map called "gameplay" with a "move" action of type Vector2.
public class MyBehavior : MonoBehaviour
{
public MyControls controls;
public float moveSpeed = 4;
protected void Awake()
{
controls = new MyControls();
}
protected void OnEnable()
{
controls.gameplay.Enable();
}
protected void OnDisable()
{
controls.gameplay.Disable();
}
protected void Update()
{
var moveVector = controls.gameplay.move.ReadValue<Vector2>() * (moveSpeed * Time.deltaTime);
//...
}
}
If the action has button-like behavior, then triggered is usually a better alternative to reading out a float and checking if it is above the button press point.
Exceptions
Type | Condition |
---|---|
InvalidOperationException | The given |
See Also
ReadValueAsObject()
Same as ReadValue<TValue>() but read the value without having to know the value type of the action.
Declaration
public object ReadValueAsObject()
Returns
Type | Description |
---|---|
Object | The current value of the action or null if the action is not currently in Started or Performed phase. |
Remarks
This method allocates GC memory and is thus not a good choice for getting called as part of gameplay logic.
See Also
ToString()
Return a string version of the action. Mainly useful for debugging.
Declaration
public override string ToString()
Returns
Type | Description |
---|---|
String | A string version of the action. |
Overrides
Events
canceled
Event that is triggered when the action has been started but then canceled before being fully performed.
Declaration
public event Action<InputAction.CallbackContext> canceled
Event Type
Type | Description |
---|---|
Action<InputAction.CallbackContext> |
Remarks
See phase for details of how an action progresses through phases and triggers this callback.
performed
Event that is triggered when the action has been fully performed.
Declaration
public event Action<InputAction.CallbackContext> performed
Event Type
Type | Description |
---|---|
Action<InputAction.CallbackContext> |
Remarks
See phase for details of how an action progresses through phases and triggers this callback.
started
Event that is triggered when the action has been started.
Declaration
public event Action<InputAction.CallbackContext> started
Event Type
Type | Description |
---|---|
Action<InputAction.CallbackContext> |
Remarks
See phase for details of how an action progresses through phases and triggers this callback.
Explicit Interface Implementations
ICloneable.Clone()
Declaration
object ICloneable.Clone()
Returns
Type | Description |
---|---|
Object |