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 (that is, 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.
To map a control in this array to an index into bindings, use GetBindingIndexForControl(InputAction, InputControl).
// Map control list to binding indices.
var bindingIndices = myAction.controls.Select(c => myAction.GetBindingIndexForControl(c));
Note that this array will not contain the same control multiple times even if more than one binding on an action references the same control.
var action1 = new InputAction();
action1.AddBinding("<Gamepad>/buttonSouth");
action1.AddBinding("<Gamepad>/buttonSouth"); // This binding will be ignored.
// Contains only one instance of buttonSouth which is associated
// with the first binding (at index #0).
var action1Controls = action1.controls;
var action2 = new InputAction();
action2.AddBinding("<Gamepad>/buttonSouth");
// Add a binding that implicitly matches the first binding, too. When binding resolution
// happens, this binding will only receive buttonNorth, buttonWest, and buttonEast, but not
// buttonSouth as the first binding already received that control.
action2.AddBinding("<Gamepad>/button*");
// Contains only all four face buttons (buttonSouth, buttonNorth, buttonEast, buttonWest)
// but buttonSouth is associated with the first button and only buttonNorth, buttonEast,
// and buttonWest are associated with the second binding.
var action2Controls = action2.controls;
See Also
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.
inProgress
Declaration
public bool inProgress { get; }
Property Value
Type | Description |
---|---|
Boolean |
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 (defaultButtonPressPoint) has been crossed.
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
Equivalent to WasPerformedThisFrame().
Declaration
public bool triggered { get; }
Property Value
Type | Description |
---|---|
Boolean |
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.
wantsInitialStateCheck
Whether the action wants a state check on its bound controls as soon as it is enabled. This is always true for Value actions but can optionally be enabled for Button or PassThrough actions.
Declaration
public bool wantsInitialStateCheck { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
Remarks
Usually, when an action is enabled (e.g. via Enable()), it will start listening for input and then trigger once the first input arrives. However, controls bound to an action may already be actuated when an action is enabled. For example, if a "jump" action is bound to spaceKey, the space bar may already be pressed when the jump action is enabled.
Value actions handle this differently by immediately performing an "initial state check" in the next input update (see Update()) after being enabled. If any of the bound controls is already actuated, the action will trigger right away -- even with no change in state on the controls.
This same behavior can be enabled explicitly for Button and PassThrough actions using this property.
See Also
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
GetTimeoutCompletionPercentage()
Return the completion percentage of the timeout (if any) running on the current interaction.
Declaration
public float GetTimeoutCompletionPercentage()
Returns
Type | Description |
---|---|
Single | A value >= 0 (no progress) and <= 1 (finished) indicating the level of completion of the currently running timeout. |
Remarks
This method is useful, for example, when providing UI feedback for an ongoing action. If, say, you have a HoldInteraction on a binding, you might want to show a progress indicator in the UI and need to know how far into the hold the action current is. Once the hold has been started, this method will return how far into the hold the action currently is.
Note that if an interaction performs and stays performed (see PerformedAndStayPerformed()), the completion percentage will remain at 1 until the interaction is canceled.
Also note that completion is based on the progression of time and not dependent on input updates. This means that if, for example, the timeout for a HoldInteraction has expired according the current time but the expiration has not yet been processed by an input update (thus causing the hold to perform), the returned completion percentage will still be 1. In other words, there isn't always a correlation between the current completion percentage and phase.
The meaning of the timeout is dependent on the interaction in play. For a HoldInteraction, the timeout represents "completion" (that is, the time until a "hold" is considered to be performed), whereas for a TapInteraction it represents "time to failure" (that is, the remaining time window that the interaction can be completed within).
Note that an interaction might run multiple timeouts in succession. One such example is MultiTapInteraction.
In this case, progression towards a single timeout does not necessarily mean progression towards completion
of the whole interaction. An interaction can call SetTotalTimeoutCompletionTime(Single)
to inform the Input System of the total length of timeouts to run. If this is done, the result of the
GetTimeoutCompletionPercentage
method will return a value reflecting the progression with respect
to total time.
// Scale a UI element in response to the completion of a hold on the gamepad's A button.
Transform uiObjectToScale;
InputAction holdAction;
void OnEnable()
{
if (holdAction == null)
{
// Create hold action with a 2 second timeout.
// NOTE: Here we create the action in code. You can, of course, grab the action from an .inputactions
// asset created in the editor instead.
holdAction = new InputAction(type: InputActionType.Button, interactions: "hold(duration=2)");
// Show the UI object when the hold starts and hide it when it ends.
holdAction.started += _ => uiObjectToScale.SetActive(true);
holdAction.canceled += _ => uiObjectToScale.SetActive(false);
// If you want to play a visual effect when the action performs, you can initiate from
// the performed callback.
holdAction.performed += _ => /* InitiateVisualEffectWhenHoldIsComplete() */;
}
holdAction.Enable();
// Hide the UI object until the action is started.
uiObjectToScale.gameObject.SetActive(false);
}
void OnDisable()
{
holdAction.Disable();
}
void Update()
{
var completion = holdAction.GetTimeoutCompletionPercentage();
uiObjectToScale.localScale = new Vector3(1, completion, 1);
}
See Also
IsInProgress()
Declaration
public bool IsInProgress()
Returns
Type | Description |
---|---|
Boolean | True if the action is currently triggering. |
See Also
IsPressed()
Check whether the current actuation of the action has crossed the button press threshold (see defaultButtonPressPoint) and has not yet fallen back below the release threshold (see buttonReleaseThreshold).
Declaration
public bool IsPressed()
Returns
Type | Description |
---|---|
Boolean | True if the action is considered to be in "pressed" state, false otherwise. |
Remarks
This method is different from simply reading the action's current float
value and comparing
it to the press threshold and is also different from comparing the current actuation of
activeControl to it. This is because the current level of actuation might have already
fallen below the press threshold but might not yet have reached the release threshold.
This method works with any type of action, not just buttons.
Also note that because this operates on the results of EvaluateMagnitude(), it works with many kind of controls, not just buttons. For example, if an action is bound to a StickControl, the control will be considered "pressed" once the magnitude of the Vector2 of the control has crossed the press threshold.
Finally, note that custom button press points of controls (see pressPoint) are respected and will take precedence over defaultButtonPressPoint.
var up = playerInput.actions["up"];
if (up.IsPressed())
transform.Translate(0, 10 * Time.deltaTime, 0);
Disabled actions will always return false from this method, even if a control bound to the action is currently pressed. Also, re-enabling an action will not restore the state to when the action was disabled even if the control is still actuated.
See Also
ReadValue<TValue>()
Read the current value of the control that is driving this action. If no bound control is actuated, returns default(TValue), but note that binding processors are always applied.
Declaration
public TValue ReadValue<TValue>()
where TValue : struct
Returns
Type | Description |
---|---|
TValue | The current value of the control/binding that is driving this action with all binding processors applied. |
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 |
Remarks
This method allocates GC memory and is thus not a good choice for getting called as part of gameplay logic.
See Also
Reset()
Reset the action state to default.
Declaration
public void Reset()
Remarks
This method can be used to forcibly cancel an action even while it is in progress. Note that unlike disabling an action, for example, this also effects APIs such as WasPressedThisFrame().
Note that invoking this method will not modify enabled state.
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
WasPerformedThisFrame()
Declaration
public bool WasPerformedThisFrame()
Returns
Type | Description |
---|---|
Boolean | True if the action performed this frame. |
Remarks
This method is different from WasPressedThisFrame() in that it depends directly on the interaction(s) driving the action (including the default interaction if no specific interaction has been added to the action or binding).
For example, let's say the action is bound to the space bar and that the binding has a
HoldInteraction assigned to it. In the frame where the space bar
is pressed, WasPressedThisFrame() will be true (because the button/key is now pressed)
but WasPerformedThisFrame
will still be false (because the hold has not been performed yet).
Only after the hold time has expired will WasPerformedThisFrame
be true and only in the frame
where the hold performed.
This is different from checking phase directly as the action might have already progressed
to a different phase after performing. In other words, even if an action performed in a frame, phase
might no longer be Performed, whereas WasPerformedThisFrame
will remain
true for the entirety of the frame regardless of what else the action does.
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 (that is, until the next Update() runs) as long as the action was triggered at least once.
var warp = playerInput.actions["Warp"];
if (warp.WasPerformedThisFrame())
InitiateWarp();
This method will disregard whether the action is currently enabled or disabled. It will keep returning true for the duration of the frame even if the action was subsequently disabled in the frame.
The meaning of "frame" is either the current "dynamic" update (MonoBehaviour.Update
) or the current
fixed update (MonoBehaviour.FixedUpdate
) depending on the value of the updateMode setting.
See Also
WasPressedThisFrame()
Returns true if the action's value crossed the press threshold (see defaultButtonPressPoint) at any point in the frame.
Declaration
public bool WasPressedThisFrame()
Returns
Type | Description |
---|---|
Boolean | True if the action was pressed this frame. |
Remarks
This method is different from WasPerformedThisFrame() in that it is not bound to phase. Instead, if the action's level of actuation (that is, the level of magnitude -- see EvaluateMagnitude() -- of the control(s) bound to the action) crossed the press threshold (see defaultButtonPressPoint) at any point in the frame, this method will return true. It will do so even if there is an interaction on the action that has not yet performed the action in response to the press.
This method works with any type of action, not just buttons.
Also note that because this operates on the results of EvaluateMagnitude(), it works with many kind of controls, not just buttons. For example, if an action is bound to a StickControl, the control will be considered "pressed" once the magnitude of the Vector2 of the control has crossed the press threshold.
Finally, note that custom button press points of controls (see pressPoint) are respected and will take precedence over defaultButtonPressPoint.
var fire = playerInput.actions["fire"];
if (fire.WasPressedThisFrame() && fire.IsPressed())
StartFiring();
else if (fire.WasReleasedThisFrame())
StopFiring();
This method will disregard whether the action is currently enabled or disabled. It will keep returning true for the duration of the frame even if the action was subsequently disabled in the frame.
The meaning of "frame" is either the current "dynamic" update (MonoBehaviour.Update
) or the current
fixed update (MonoBehaviour.FixedUpdate
) depending on the value of the updateMode setting.
See Also
WasReleasedThisFrame()
Returns true if the action's value crossed the release threshold (see buttonReleaseThreshold) at any point in the frame after being in pressed state.
Declaration
public bool WasReleasedThisFrame()
Returns
Type | Description |
---|---|
Boolean | True if the action was released this frame. |
Remarks
This method works with any type of action, not just buttons.
Also note that because this operates on the results of EvaluateMagnitude(), it works with many kind of controls, not just buttons. For example, if an action is bound to a StickControl, the control will be considered "pressed" once the magnitude of the Vector2 of the control has crossed the press threshold.
Finally, note that custom button press points of controls (see pressPoint) are respected and will take precedence over defaultButtonPressPoint.
var fire = playerInput.actions["fire"];
if (fire.WasPressedThisFrame() && fire.IsPressed())
StartFiring();
else if (fire.WasReleasedThisFrame())
StopFiring();
This method will disregard whether the action is currently enabled or disabled. It will keep returning true for the duration of the frame even if the action was subsequently disabled in the frame.
The meaning of "frame" is either the current "dynamic" update (MonoBehaviour.Update
) or the current
fixed update (MonoBehaviour.FixedUpdate
) depending on the value of the updateMode setting.
See Also
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 |