From 81ad12f3ef01640ae0c4a32feff3f84cf47d2f17 Mon Sep 17 00:00:00 2001 From: Ben Pitt Date: Fri, 6 Sep 2024 13:26:12 +0100 Subject: [PATCH 1/9] content model re-org WIP --- .../Documentation~/ActionAssets.md | 56 ++++++-- .../Documentation~/ActionBindings.md | 72 ++++++---- .../Documentation~/ActionProperties.md | 4 + .../Documentation~/ActionsEditor.md | 9 +- .../AssignProjectWideActions.md | 14 ++ .../Documentation~/ConfigureActions.md | 6 + .../Documentation~/ControlSchemes.md | 9 ++ .../Documentation~/CreateActionAsset.md | 41 ++++++ .../Documentation~/CreateActionMaps.md | 12 ++ .../Documentation~/CreateActions.md | 126 ++++++++++++++++++ .../Documentation~/DefaultActions.md | 16 +++ .../Documentation~/GetInfoAboutDevices.md | 0 .../Documentation~/Interactions.md | 31 +++-- .../Documentation~/ProjectWideActions.md | 39 ------ .../Documentation~/SettingUpInput.md | 22 +++ .../Documentation~/TableOfContents.md | 20 +++ 16 files changed, 378 insertions(+), 99 deletions(-) create mode 100644 Packages/com.unity.inputsystem/Documentation~/ActionProperties.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/AssignProjectWideActions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/ConfigureActions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/ControlSchemes.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/CreateActionAsset.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/CreateActionMaps.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/CreateActions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/DefaultActions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/GetInfoAboutDevices.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/SettingUpInput.md diff --git a/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md b/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md index def2c2e5e5..1e8207c5a1 100644 --- a/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md +++ b/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md @@ -3,27 +3,65 @@ uid: input-system-action-assets --- # Input Action Assets -- [Creating Input Action Assets](#creating-input-action-assets) -- [Editing Input Action Assets](#editing-input-action-assets) + +# Concept title + +First line: Summarize purpose of page in one sentence, starting with +an active verb. No links or formatting. + +One to three paragraphs: Introduce the key takeaways of the body content, in +order of appearance. No headings, images, or tables. + +Final paragraph (optional): Links to related documentation the user +might be looking for instead. + +## Descriptive heading + +Use descriptive headings to break up the content and make the page easy to +scan. Organize content logically and introduce ideas gradually. + +### Detailed heading + +Don't use headings below H3 level. + +## Additional resources + +- [Link](related-content-on-Unity-owned-platforms) +- [Link](related-content-on-Unity-owned-platforms) + +-------------------------------------------- + + +- [Descriptive heading](#descriptive-heading) + - [Detailed heading](#detailed-heading) +- [Additional resources](#additional-resources) +- [Project-Wide Actions](#project-wide-actions) - [Using Input Action Assets](#using-input-action-assets) - [Type-safe C# API Generation](#type-safe-c-api-generation) + - [Auto-generating script code for Actions](#auto-generating-script-code-for-actions) + - [Using Action Assets with `PlayerInput`](#using-action-assets-with-playerinput) + - [Modifying Input Action Assets at runtime](#modifying-input-action-assets-at-runtime) + - [The Default Actions Asset](#the-default-actions-asset) + +The Input System stores your configuration of [Input Actions](Actions.md) and their associated [Bindings](ActionBindings.md), [Action Maps](ActionsEditor.html#configure-action-maps) and [Control Schemes](ActionBindings.md#control-schemes) in an [Action Asset](ActionAssets.md) file. + +While it's possible to have more than one Action Asset in a project, most projects only ever need a single Action Asset. -An Input Action Asset is an Asset which contains a set of [Input Actions](Actions.md) definitions and their associated [Bindings](ActionBindings.md) and [Control Schemes](ActionBindings.md#control-schemes). These Assets have the `.inputactions` file extension and are stored in a plain JSON format. +These Assets have the `.inputactions` file extension and are stored in a plain JSON format. The input system creates an Action Asset when you set up the [default project-wide actions](ProjectWideActions.md), but you can also create new Action Assets directly in the Project window. -For most common scenarios, you do not need to use more than one Input Action Asset. It is usually simpler to configure your project-wide action definition in the Project Settings window. +For most common scenarios, you do not need to use more than one Input Action Asset. This is because an Action Asset can contain multiple [Action Maps](ActionsEditor.html#configure-action-maps), which each containing a set of actions relevant to the various parts of your project (such as UI navigation, gameplay, etc). +## Project-Wide Actions -## Creating Input Action Assets +The Input System's **project-wide actions** feature allows you to choose an individual Action Asset to be available project-wide, which means the actions within that asset are available more conveniently through the Input System API without needing to set up references to a specific asset. -To create an Asset that contains [Input Actions](Actions.md) in Unity, right-click in the __Project__ window or go to __Assets > Create > Input Actions__ from Unity's main menu. +When you assign an Action Asset as project-wide, it also becomes automatically [preloaded](https://docs.unity3d.com/ScriptReference/PlayerSettings.GetPreloadedAssets.html) when your app starts up, and is kept available until it terminates. -## Editing Input Action Assets +Unless you have specific project requirements that require more than one Action Asset, the recommended workflow is to use a single Action Asset assigned as the project-wide actions. -To bring up the Action editor, double-click an `.inputactions` Asset in the Project Browser, or select the __Edit Asset__ button in the Inspector for that Asset. You can have more than one editor window open at the same time, but not for the same Asset. -The Actions Editor which opens is identical to the [Actions Editor in the Project Settings window](ActionsEditor.md). ## Using Input Action Assets diff --git a/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md b/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md index 9c164e2439..3960ed7817 100644 --- a/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md +++ b/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md @@ -1,33 +1,51 @@ --- uid: input-system-action-bindings --- -# Input Bindings - -* [Composite Bindings](#composite-bindings) - * [1D Axis](#1d-axis) - * [2D Vector](#2d-vector) - * [3D Vector](#3d-vector) - * [One Modifier](#one-modifier) - * [Two Modifiers](#two-modifiers) - * [Writing custom Composites](#writing-custom-composites) -* [Working with Bindings](#working-with-bindings) - * [Looking up Bindings](#looking-up-bindings) - * [Changing Bindings](#changing-bindings) - * [Applying overrides](#applying-overrides) - * [Erasing Bindings](#erasing-bindings) - * [Adding Bindings](#adding-bindings) - * [Setting parameters](#setting-parameters) - * [Interactive rebinding](#interactive-rebinding) - * [Saving and loading rebinds](#saving-and-loading-rebinds) - * [Restoring original Bindings](#restoring-original-bindings) - * [Displaying Bindings](#displaying-bindings) -* [Control schemes](#control-schemes) -* [Details](#details) - * [Binding resolution](#binding-resolution) - * [Binding resolution while Actions are enabled](#binding-resolution-while-actions-are-enabled) - * [Choosing which Devices to use](#choosing-which-devices-to-use) - * [Conflicting inputs](#conflicting-inputs) - * [Initial state check](#initial-state-check) +# Action Bindings + +- [Composite Bindings](#composite-bindings) + - [1D axis](#1d-axis) + - [2D vector](#2d-vector) + - [3D vector](#3d-vector) + - [One Modifier](#one-modifier) + - [Two Modifiers](#two-modifiers) + - [Writing custom Composites](#writing-custom-composites) +- [Working with Bindings](#working-with-bindings) +- [Looking up Bindings](#looking-up-bindings) +- [Changing Bindings](#changing-bindings) + - [Applying overrides](#applying-overrides) + - [Erasing Bindings](#erasing-bindings) + - [Adding Bindings](#adding-bindings) + - [Setting parameters](#setting-parameters) +- [Interactive rebinding](#interactive-rebinding) +- [Saving and loading rebinds](#saving-and-loading-rebinds) + - [Restoring original Bindings](#restoring-original-bindings) + - [Displaying Bindings](#displaying-bindings) +- [Control Schemes](#control-schemes) +- [Details](#details) + - [Binding resolution](#binding-resolution) + - [Conflicting inputs](#conflicting-inputs) + - [Initial state check](#initial-state-check) + + +### Bindings + +* To add a new Binding, select the Add (+) icon on the action you want to add it to, and select the binding type from the menu that appears. +* To delete an existing Binding, either right-click it and select __Delete__ from the context menu. +* To duplicate an existing Binding, either right-click it and select __Duplicate__ from the context menu. + +You can add multiple bindings to an action, which is generally useful for supporting multiple types of input device. For example, in the default set of actions, the "Move" action has a binding to the left gamepad stick and the WSAD keys, which means input through any of these bindings will perform the action. + +![The default "move" action with its multiple bindings highlighted](./Images/ActionWithMultipleBindings.png)
+_The default "Move" action in the Actions Editor window, displaying the multiple bindings associated with it._ + +If you select a Binding, you can edit its properties in the right-hand pane of the window: + +![Binding Properties](Images/BindingProperties.png) + + + + An [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html) represents a connection between an [Action](Actions.md) and one or more [Controls](Controls.md) identified by a [Control path](Controls.md#control-paths). For example, the **right trigger** of a gamepad (a control) might be bound to an an action named "accelerate", so that pulling the right trigger causes a car to accelerate in your game. diff --git a/Packages/com.unity.inputsystem/Documentation~/ActionProperties.md b/Packages/com.unity.inputsystem/Documentation~/ActionProperties.md new file mode 100644 index 0000000000..40bf2675cb --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/ActionProperties.md @@ -0,0 +1,4 @@ +# Action Properties + +Action properties are the details about an action which describe the type of control it relates to, as well as some optional properties such as Interactions and Processors assigned to the action. + diff --git a/Packages/com.unity.inputsystem/Documentation~/ActionsEditor.md b/Packages/com.unity.inputsystem/Documentation~/ActionsEditor.md index 39ac1fe4b6..a84897b35c 100644 --- a/Packages/com.unity.inputsystem/Documentation~/ActionsEditor.md +++ b/Packages/com.unity.inputsystem/Documentation~/ActionsEditor.md @@ -7,7 +7,7 @@ The **Input Actions Editor** allows you to edit [Action Assets](ActionAssets.md) It allows you to group collections of Actions into [Action Maps](ActionsEditor.html#configure-action-maps), which represent different input scenarios in your project (such as UI navigation, gameplay, etc.) -It also alows you to define [Control Schemes](ActionBindings.md#control-schemes) which are a way to enable or disable a set of devices, or respond to which type of device is being used. This is often useful if you want to customise your UI based on whether your users are using mouse, keyboard, or gamepad as their chosen input. +It also allows you to define [Control Schemes](ActionBindings.md#control-schemes) which are a way to enable or disable a set of devices, or respond to which type of device is being used. This is often useful if you want to customise your UI based on whether your users are using mouse, keyboard, or gamepad as their chosen input. ### Action Assets and Project-Wide Actions @@ -32,12 +32,6 @@ The Input Actions editor is divided into three panels (marked A, B & C above). |**(B) Actions**|Displays all the actions defined in the currently selected Action Map, and the bindings associated with each Action.| |**(C) Properties**|Displays the properties of the currently selected Action or Binding from the Actions panel. The title of this panel changes depending on whether you have an Action or a Binding selected in the Actions panel.| -### Configure Action Maps - -* To add a new Action Map, select the Add (+) icon in the header of the Action Map panel. -* To rename an existing Action Map, either long-click the name, or right-click the Action Map and select __Rename__ from the context menu. Note that Action Map names can't contain slashes (`/`). -* To delete an existing Action Map, right-click it and select __Delete__ from the context menu. -* To duplicate an existing Action Map, right-click it and select __Duplicate__ from the context menu. ### Configure Actions @@ -45,7 +39,6 @@ The Input Actions editor is divided into three panels (marked A, B & C above). * To rename an existing Action, either long-click the name, or right-click the Action Map and select __Rename__ from the context menu. * To delete an existing Action, either right-click it and select __Delete__ from the context menu. * To duplicate an existing Action, either right-click it and select __Duplicate__ from the context menu. -* ## Action type and Control type diff --git a/Packages/com.unity.inputsystem/Documentation~/AssignProjectWideActions.md b/Packages/com.unity.inputsystem/Documentation~/AssignProjectWideActions.md new file mode 100644 index 0000000000..8ae667326d --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/AssignProjectWideActions.md @@ -0,0 +1,14 @@ +# Assign project-wide actions + +To assign an existing Actions Asset as project-wide, do one of the following: + +- Go to **Edit** > **Project Settings** > **Input System Package**, then drag the asset from your Project window into the **Project-wide Actions** field. +![image alt text](./Images/InputSettingsNoProjectWideAsset.png)
+*The Input System Package Project Settings with no project-wide actions assigned* + +or: + +- Select the Asset in your Project window, then in the Inspector window, select **Assign as the Project-wide Input Actions**. + + +Only one Actions Asset can be assigned as project-wide. If a different asset was previously assigned as project-wide, it becomes unassigned. \ No newline at end of file diff --git a/Packages/com.unity.inputsystem/Documentation~/ConfigureActions.md b/Packages/com.unity.inputsystem/Documentation~/ConfigureActions.md new file mode 100644 index 0000000000..dcff8c4142 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/ConfigureActions.md @@ -0,0 +1,6 @@ +# Configure Actions + +* To add a new Action, select the Add (+) icon in the header of the Action column. +* To rename an existing Action, either long-click the name, or right-click the Action Map and select __Rename__ from the context menu. +* To delete an existing Action, either right-click it and select __Delete__ from the context menu. +* To duplicate an existing Action, either right-click it and select __Duplicate__ from the context menu. diff --git a/Packages/com.unity.inputsystem/Documentation~/ControlSchemes.md b/Packages/com.unity.inputsystem/Documentation~/ControlSchemes.md new file mode 100644 index 0000000000..c5990b75e3 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/ControlSchemes.md @@ -0,0 +1,9 @@ +# Editing Control Schemes + +Input Action Assets can have multiple [Control Schemes](ActionBindings.md#control-schemes), which let you enable or disable different sets of Bindings for your Actions for different types of Devices. + +![Control Scheme Properties](Images/ControlSchemeProperties.png) + +To see the Control Schemes in the Input Action Asset editor window, open the Control Scheme drop-down list in the top left of the window. This menu lets you add or remove Control Schemes to your Actions Asset. If the Actions Asset contains any Control Schemes, you can select a Control Scheme, and then the window only shows bindings that are associated with that Scheme. If you select a binding, you can now pick the Control Schemes for which this binding should be active in the __Properties__ view to the left of the window. + +When you add a new Control Scheme, or select an existing Control Scheme, and then select __Edit Control Scheme__, you can edit the name of the Control Scheme and which devices the Scheme should be active for. When you add a new Control Scheme, the "Device Type" list is empty by default (as shown above). You must add at least one type of device to this list for the Control Scheme to be functional. diff --git a/Packages/com.unity.inputsystem/Documentation~/CreateActionAsset.md b/Packages/com.unity.inputsystem/Documentation~/CreateActionAsset.md new file mode 100644 index 0000000000..993c12ba78 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/CreateActionAsset.md @@ -0,0 +1,41 @@ +# Create an action asset + +In most cases, you only need one Action Asset, assigned as the project-wide actions. The input package provides a convenient way to create a set of useful default actions and assign them as project-wide. In other cases, you might want to start with an empty actions asset, or create more than one actions asset. + +## Create and assign a default project-wide actions asset + +Follow these steps to create an actions asset that contains the built-in [default actions](./TheDefaultActions.md), and assign them as project-wide. + +Open the Input System Package panel in Project Settings, by going to **Edit** > **Project Settings** > **Input System Package**. + +If you don't yet have an Action Asset assigned as project-wide in your project, the Input System Package settings window displays an empty field for you to assign your action asset, and a button allowing you to create and assign one. + +![image alt text](./Images/InputSettingsNoProjectWideAsset.png)
+*The Input System Package Project Settings with no project-wide actions assigned* + +> **Note:** If you already have an Action Asset assigned, this button is not displayed, and instead the Actions Editor is displayed, allowing you to edit the project-wide actions. + +Click **"Create a new project-wide Action Asset"**. + +The asset is created in your project, and automatically assigned as the **project-wide actions**. + +The Action Asset appears in your Project view, and is named "InputSystem_Actions". This is where your new configuration of actions is saved, including any changes you make to it. + +![](images/InputSystemActionsAsset.png)
+*The new Actions Asset in your Project window* + +When you create an action asset this way, the new asset contains a set of default actions that are useful in many common scenarios. You can [configure them](./ConfigureActions.md) or [add new actions](./CreateActions.md) to suit your project. + +![image alt text](./Images/ProjectSettingsInputActionsSimpleShot.png) +*The Input System Package Project Settings after creating and assigning the default actions* + +Once you have created and assigned project-wide actions, the Input System Package page in Project Settings displays the **Actions Editor** interface. Read more about how to use the [Actions Editor](ActionsEditor.md) to configure your actions. + +## Create a new empty input action asset + +In some situations you might want to start with an empty action asset, or create additional action assets. + +To do this, go to __Assets > Create > Input Actions__ from Unity's main menu, or select **Input Actions** the Project window's **Add (+)** button menu. + +When you create an action asset this way, the new action asset is empty, containing no actions, action maps, or control schemes. You must [add](./CreateActions.md) and [configure](./ConfigureActions.md) new actions to use it. The new action asset is also not assigned as [project-wide](./ProjectWideActions.md). + diff --git a/Packages/com.unity.inputsystem/Documentation~/CreateActionMaps.md b/Packages/com.unity.inputsystem/Documentation~/CreateActionMaps.md new file mode 100644 index 0000000000..42ff282ce8 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/CreateActionMaps.md @@ -0,0 +1,12 @@ +# Create Action Maps + +Action maps provide a way to group collections of Actions that represent different input scenarios in your project (such as UI navigation, gameplay, etc.) + +Actions must belong to an Action Map, therefore if you are starting with an empty Actions Asset, you must create an action map before you can create any actions. + +The Action Maps section of the Actions Editor allows you to create, rename, delete, and duplicate Action Maps. + +* To add a new Action Map, select the Add (+) icon in the header of the Action Map panel. +* To rename an existing Action Map, either long-click the name, or right-click the Action Map and select __Rename__ from the context menu. Note that Action Map names can't contain slashes (`/`). +* To delete an existing Action Map, right-click it and select __Delete__ from the context menu. +* To duplicate an existing Action Map, right-click it and select __Duplicate__ from the context menu. diff --git a/Packages/com.unity.inputsystem/Documentation~/CreateActions.md b/Packages/com.unity.inputsystem/Documentation~/CreateActions.md new file mode 100644 index 0000000000..e60d051eb2 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/CreateActions.md @@ -0,0 +1,126 @@ + +# Create Actions + +The simplest way to create actions is to use the [Input Actions editor](ActionsEditor.md) in the Project Settings window. This is the primary recommended workflow and suitable for most scenarios. + +However, because the input system API is very open, there are many other ways to create actions which may suit less common scenarios. For example, by loading actions from JSON data, or creating actions entirely in code. + +### Create Actions using the Action editor + +For information on how to create and edit Input Actions in the editor, see the [Input Actions editor](ActionsEditor.md). This is the recommended workflow if you want to organise all your input actions and bindings in one place, which applies across the whole of your project. This often the case for most types of game or app. + +![Action Editor Window](Images/ProjectSettingsInputActionsSimpleShot.png) +*The Input Actions Editor in the Project Settings window* + + +### Configure Actions + +* To add a new Action, select the Add (+) icon in the header of the Action column. +* To rename an existing Action, either long-click the name, or right-click the Action Map and select __Rename__ from the context menu. +* To delete an existing Action, either right-click it and select __Delete__ from the context menu. +* To duplicate an existing Action, either right-click it and select __Duplicate__ from the context menu. + + + + + +## Other ways to create Actions + +The simplest way to create actions is to use the [Input Actions editor](ActionsEditor.md) to configure a set of actions in an asset, as described above. However, because the Input System package API is open and flexible, you can create actions using alternative techniques. These alternatives might be more suitable if you want to customize your project beyond the standard workflow. + +### Creating Actions by declaring them in MonoBehaviours + +As an alternative workflow, you can declare individual [Input Action](../api/UnityEngine.InputSystem.InputAction.html) and [Input Action Maps](../api/UnityEngine.InputSystem.InputActionMap.html) as fields directly inside `MonoBehaviour` components. + +```CSharp +using UnityEngine; +using UnityEngine.InputSystem; + +public class ExampleScript : MonoBehaviour +{ + public InputAction move; + public InputAction jump; +} +``` + +The result is similar to using an Actions defined in the Input Actions editor, except the Actions are defined in the GameObject's properties and saved as Scene or Prefab data, instead of in a dedicated Asset. + +When you embed actions like this, by defining serialized InputAction fields in a MonoBehaviour, the GameObject's Inspector window displays an interface similar to the Actions column of the [Actions Editor](./ActionsEditor.md), which allows you to set up the bindings for those actions. For example: + +![MyBehavior Inspector](Images/Workflow-EmbeddedActionsInspector.png) + +* To add or remove Actions or Bindings, click the Add (+) or Remove (-) icon in the header. +* To edit Bindings, double-click them.
+* To edit Actions, double-click them in an Action Map, or click the gear icon on individual Action properties.
+* You can also right-click entries to bring up a context menu, and you can drag them. Hold the Alt key and drag an entry to duplicate it. + +Unlike the project-wide actions in the Project Settings window, you must manually enable and disable Actions and Action Maps that are embedded in MonoBehaviour components. + +When you use this workflow, the serialised action configurations are stored with the parent GameObject as part of the scene, opposite to being serialised with an Action Asset. This can be useful if you want to bundle the control bindings and behaviour together in a single monobehaviour or prefab, so it can be distributed together. However, this can also make it harder to organize your full set of control bindings if they are distributed across multiple prefabs or scenes. + +### Loading Actions from JSON + +You can load Actions as JSON in the form of a set of Action Maps or as a full [`InputActionAsset`](../api/UnityEngine.InputSystem.InputActionAsset.html). This also works at runtime in the Player. + +```CSharp +// Load a set of action maps from JSON. +var maps = InputActionMap.FromJson(json); + +// Load an entire InputActionAsset from JSON. +var asset = InputActionAsset.FromJson(json); +``` + +### Creating Actions in code + +You can manually create and configure Actions entirely in code, including assigning the bindings. This also works at runtime in the Player. For example: + +```CSharp +// Create free-standing Actions. +var lookAction = new InputAction("look", binding: "/leftStick"); +var moveAction = new InputAction("move", binding: "/rightStick"); + +lookAction.AddBinding("/delta"); +moveAction.AddCompositeBinding("Dpad") + .With("Up", "/w") + .With("Down", "/s") + .With("Left", "/a") + .With("Right", "/d"); + +// Create an Action Map with Actions. +var map = new InputActionMap("Gameplay"); +var lookAction = map.AddAction("look"); +lookAction.AddBinding("/leftStick"); + +// Create an Action Asset. +var asset = ScriptableObject.CreateInstance(); +var gameplayMap = new InputActionMap("gameplay"); +asset.AddActionMap(gameplayMap); +var lookAction = gameplayMap.AddAction("look", "/leftStick"); +``` + +Any action that you create in this way during Play mode do not persist in the Input Action Asset after you exit Play mode. This means you can test your application in a realistic manner in the Editor without having to worry about inadvertently modifying the asset. + + +## Enabling actions + +Actions have an **enabled** state, meaning you can enable or disable them to suit different situations. + +If you have an Action Asset assigned as [project-wide](./ProjectWideActions.md), the actions it contains are enabled by default and ready to use. + +For actions defined elsewhere, such as in an Action Asset not assigned as project-wide, or defined your own code, they begin in a disabled state, and you must enable them before they will respond to input. + +You can enable actions individually, or as a group by enabling the Action Map which contains them. + +```CSharp +// Enable a single action. +lookAction.Enable(); + +// Enable an en entire action map. +gameplayActions.Enable(); +``` + +When you enable an Action, the Input System resolves its bindings, unless it has done so already, or if the set of devices that the Action can use has not changed. For more details about this process, see the documentation on [binding resolution](ActionBindings.md#binding-resolution). + +You can't change certain aspects of the configuration, such Action Bindings, while an Action is enabled. To stop Actions or Action Maps from responding to input, call [`Disable`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_Disable). + +While enabled, an Action actively monitors the [Control(s)](Controls.md) it's bound to. If a bound Control changes state, the Action processes the change. If the Control's change represents an [Interaction](Interactions.md) change, the Action creates a response. All of this happens during the Input System update logic. Depending on the [update mode](Settings.md#update-mode) selected in the input settings, this happens once every frame, once every fixed update, or manually if updates are set to manual. diff --git a/Packages/com.unity.inputsystem/Documentation~/DefaultActions.md b/Packages/com.unity.inputsystem/Documentation~/DefaultActions.md new file mode 100644 index 0000000000..49d9b70501 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/DefaultActions.md @@ -0,0 +1,16 @@ +# The default actions + +When you [create and assign default project-wide actions](CreateActionAsset.md) the Action Asset comes pre-configured with some default Actions such as "Move", "Jump", and more, which suit many common app and game scenarios. They are configured to read input from the most common types of input controller such as Keyboard, Mouse, Gamepad, Touchscreen, and extended reality (XR). + +![image alt text](./Images/ProjectSettingsInputActionsSimpleShot.png) +*The Input System Package Project Settings after creating and assigning the default actions* + +These default actions mean that in many cases, you can start scripting with the Input System without any configuration by referring to the names of the default actions that are already configured for you. You can also rename and reconfigure the default actions, or delete these default configurations to suit your needs. + +If you’d like to delete all the default actions so that you can start from an empty configuration, you don’t need to delete the individual actions one-by-one. You can delete the each Action Map, which deletes all the Actions contained in the maps in one go. + +You can also delete all action maps, or reset all the actions back to the default values from the **more** (⋮) menu at the top right of the Input Actions section of the settings window, below the Project Settings window search field. + +![The Input Actions **more** menu as displayed in the Project Settings window](images/InputActionsSettingsMoreMenu.png) + +> **Note:** this **more** (⋮) menu is not available when the Actions Editor is open in a separate window, it is only present in the Project Settings window. \ No newline at end of file diff --git a/Packages/com.unity.inputsystem/Documentation~/GetInfoAboutDevices.md b/Packages/com.unity.inputsystem/Documentation~/GetInfoAboutDevices.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Packages/com.unity.inputsystem/Documentation~/Interactions.md b/Packages/com.unity.inputsystem/Documentation~/Interactions.md index e7933342ce..d502c8f414 100644 --- a/Packages/com.unity.inputsystem/Documentation~/Interactions.md +++ b/Packages/com.unity.inputsystem/Documentation~/Interactions.md @@ -3,22 +3,21 @@ uid: input-system-interactions --- # Interactions -- [Interactions](#interactions) - - [Operation](#operation) - - [Multiple Controls on an Action](#multiple-controls-on-an-action) - - [Multiple Interactions on a Binding](#multiple-interactions-on-a-binding) - - [Timeouts](#timeouts) - - [Using Interactions](#using-interactions) - - [Interactions applied to Bindings](#interactions-applied-to-bindings) - - [Interactions applied to Actions](#interactions-applied-to-actions) - - [Predefined Interactions](#predefined-interactions) - - [Default Interaction](#default-interaction) - - [Press](#press) - - [Hold](#hold) - - [Tap](#tap) - - [SlowTap](#slowtap) - - [MultiTap](#multitap) - - [Writing custom Interactions](#writing-custom-interactions) +- [Operation](#operation) + - [Multiple Controls on an Action](#multiple-controls-on-an-action) + - [Multiple Interactions on a Binding](#multiple-interactions-on-a-binding) + - [Timeouts](#timeouts) +- [Using Interactions](#using-interactions) + - [Interactions applied to Bindings](#interactions-applied-to-bindings) + - [Interactions applied to Actions](#interactions-applied-to-actions) +- [Predefined Interactions](#predefined-interactions) + - [Default Interaction](#default-interaction) + - [Press](#press) + - [Hold](#hold) + - [Tap](#tap) + - [SlowTap](#slowtap) + - [MultiTap](#multitap) +- [Writing custom Interactions](#writing-custom-interactions) An Interaction represents a specific input pattern. For example, a [hold](#hold) is an Interaction that requires a Control to be held for at least a minimum amount of time. diff --git a/Packages/com.unity.inputsystem/Documentation~/ProjectWideActions.md b/Packages/com.unity.inputsystem/Documentation~/ProjectWideActions.md index 6248dea44f..272b5133b7 100644 --- a/Packages/com.unity.inputsystem/Documentation~/ProjectWideActions.md +++ b/Packages/com.unity.inputsystem/Documentation~/ProjectWideActions.md @@ -1,34 +1,8 @@ --- uid: project-wide-actions --- -# Project-Wide Actions -The Input System stores your configuration of [Input Actions](Actions.md) and their associated [Bindings](ActionBindings.md), [Action Maps](ActionsEditor.html#configure-action-maps) and [Control Schemes](ActionBindings.md#control-schemes) in an [Action Asset](ActionAssets.md) file. -While it's possible to have more than one Action Asset in a project, most projects only ever need a single Action Asset. This is because an Action Asset can contain multiple [Action Maps](ActionsEditor.html#configure-action-maps), which each containing a set of actions relevant to the various parts of your project (such as UI navigation, gameplay, etc). - -The Input System's **project-wide actions** feature allows you to choose an individual Action Asset as being available project-wide, which means the actions within that asset are available more conveniently through the Input System API without needing to set up a reference to the Actions Asset. - -The Action Asset assigned as project-wide is also a [preloaded asset](https://docs.unity3d.com/ScriptReference/PlayerSettings.GetPreloadedAssets.html), loaded when your app starts up, and kept available until until it terminates. - -Unless you have specific project requirements that require more than one Action Asset, the recommended workflow is to use a single Action Asset assigned as the project-wide actions, as described below. - -## Create and Assign a Project-Wide Actions Asset - -To create and assign the current project-wide actions, go to **Edit** > **Project Settings** > **Input System Package**. - -If you don't yet have an Action Asset assigned as project-wide in your project, the Input System Package settings window displays an empty field for you to assign your action asset, and a button allowing you to create and assign one. -![image alt text](./Images/InputSettingsNoProjectWideAsset.png)
-*The Input System Package Project Settings with no project-wide actions assigned* - -> **Note:** If you already have an Action Asset assigned, this button is not displayed, and instead the Actions Editor is displayed, allowing you to edit the project-wide actions. - -To create an Action Asset with default actions pre-configured, click **"Create a new project-wide Action Asset"**. The asset is created in your project, and automatically assigned as the **project-wide actions**. - -The Action Asset appears in your Project view, and is named "InputSystem_Actions". This is where your new configuration of actions is saved, including any changes you make to it. - -![](images/InputSystemActionsAsset.png)
-*The new Actions Asset in your Project window* ## Edit project-wide actions @@ -37,19 +11,6 @@ Once you have created and assigned project-wide actions, the Input System Packag ![image alt text](./Images/ProjectSettingsInputActionsSimpleShot.png) *The Input System Package Project Settings after creating and assigning the default actions* -## The default actions - -When you create and assign default project-wide actions using the method described above, the Action Asset comes pre-configured with some default Actions such as "Move", "Jump", and more, which suit many common app and game scenarios. They are configured to read input from the most common types of input controller such as Keyboard, Mouse, Gamepad, Touchscreen and XR. - -These default actions mean that in many cases, you can start scripting with the Input System without any configuration by referring to the names of the default actions that are already configured for you. You can also rename and reconfigure the default actions, or delete these default configurations to suit your needs. - -If you’d like to delete all the default actions so that you can start from an empty configuration, you don’t need to delete the individual actions one-by-one. You can delete the each Action Map, which deletes all the Actions contained in the maps in one go. - -You can also delete all action maps, or reset all the actions back to the default values from the **more** (⋮) menu at the top right of the Input Actions section of the settings window, below the Project Settings window search field. - -![The Input Actions **more** menu as displayed in the Project Settings window](images/InputActionsSettingsMoreMenu.png) - -> **Note:** this **more** (⋮) menu is not available when the Actions Editor is open in a separate window, it is only present in the Project Settings window. ## Using project-wide actions in code diff --git a/Packages/com.unity.inputsystem/Documentation~/SettingUpInput.md b/Packages/com.unity.inputsystem/Documentation~/SettingUpInput.md new file mode 100644 index 0000000000..76295d2aa3 --- /dev/null +++ b/Packages/com.unity.inputsystem/Documentation~/SettingUpInput.md @@ -0,0 +1,22 @@ +# Setting up input + +Learn how to configure input to suit the needs of your project. + +User input comes in many forms, from keyboard, mouse, gamepads, and more. Configuring input means you define the meaning of the controls on your users devices, as well as details such as + +One or two paragraphs: Describe the key themes of the subpages, and link +to background context. No headings, images, or tables. + +Final paragraph (optional): Links to related documentation the user +might be looking for instead. + +| **Topic** | **Description** | +| :------------------------------ | :------------------------------- | +| **[Subpage A](link-to-page-A)** | Summary sentence from subpage A. | +| **[Subpage B](link-to-page-B)** | Summary sentence from subpage A. | +| **...** | ... | + +## Additional resources + +- [Link](related-content-on-Unity-owned-platforms) +- [Link](related-content-on-Unity-owned-platforms) \ No newline at end of file diff --git a/Packages/com.unity.inputsystem/Documentation~/TableOfContents.md b/Packages/com.unity.inputsystem/Documentation~/TableOfContents.md index 305e0dfa9f..b9c8119668 100644 --- a/Packages/com.unity.inputsystem/Documentation~/TableOfContents.md +++ b/Packages/com.unity.inputsystem/Documentation~/TableOfContents.md @@ -7,6 +7,26 @@ * [Workflow - Actions](Workflow-Actions.md) * [Workflow - Actions & PlayerInput](Workflow-PlayerInput.md) * [Workflow - Direct](Workflow-Direct.md) +* [Setting up input](SettingUpInput.md) + * [Action Assets](ActionAssets.md) + * [Create an Action Asset](CreateAnActionAsset.md) + * [Assign a project-wide Action Asset](AssignProjectWideActionAsset.md) + * [Default actions](DefaultActions.md) + * [Actions](ActionsIntro.md) + * [Actions](Actions.md) + * [Create action maps](CreateActionMaps.md) + * [Create actions](CreateActions.md) + * [Action properties](ActionProperties.md) + * [Bindings](ActionBindings.md) + * [Controls](Controls.md) + * [Controls schemes](ControlSchemes.md) + * [Interactions](Interactions.md) + * [Processors](Processors.md) + * [Configure sctions](ConfigureActions.md) + * [The actions editor window](ActionsEditor.md) + * [Devices](Devices.md) + * [Get information about devices](GetInfoAboutDevices.md) +* [--End of TOC reorg--](index.md) * [Using the Input System]() * [Project-Wide Actions](ProjectWideActions.md) * [Configuring Input](ActionsEditor.md) From e3473b2c8cc68728d1a4cdcc5f0bcedfd4042ce8 Mon Sep 17 00:00:00 2001 From: Ben Pitt Date: Wed, 2 Oct 2024 14:27:10 +0100 Subject: [PATCH 2/9] content model re-org continued WIP --- .../Documentation~/ActionAssets.md | 158 --- .../Documentation~/ActionBindings.md | 971 ------------------ .../Documentation~/Actions.md | 139 +-- .../Documentation~/Controls.md | 275 +---- .../Documentation~/CreateActions.md | 126 --- .../Documentation~/Devices.md | 51 +- .../Documentation~/Interactions.md | 289 ------ .../Documentation~/Processors.md | 275 ----- .../Documentation~/TableOfContents.md | 42 +- .../Documentation~/action-assets.md | 64 ++ .../Documentation~/action-bindings.md | 227 ++++ ...tionProperties.md => action-properties.md} | 0 .../{ActionsEditor.md => actions-editor.md} | 5 + .../Documentation~/api-overview.md | 15 + ...ions.md => assign-project-wide-actions.md} | 0 .../binding-initial-state-checks.md | 13 + .../Documentation~/binding-overrides.md | 30 + .../Documentation~/binding-resolution.md | 43 + .../Documentation~/changing-bindings.md | 43 + .../Documentation~/composite-bindings.md | 320 ++++++ ...ions.md => configure-action-properties.md} | 2 +- .../Documentation~/control-actuation.md | 26 + .../Documentation~/control-hierarchies.md | 7 + .../Documentation~/control-paths.md | 44 + .../{ControlSchemes.md => control-schemes.md} | 0 .../Documentation~/control-state.md | 18 + .../Documentation~/control-types.md | 20 + .../Documentation~/control-usages.md | 8 + ...eActionAsset.md => create-action-asset.md} | 0 ...ateActionMaps.md => create-action-maps.md} | 0 .../Documentation~/create-actions-in-code.md | 29 + .../Documentation~/create-actions.md | 38 + .../dealing-with-binding-conflicts.md | 124 +++ .../{DefaultActions.md => default-actions.md} | 19 +- .../Documentation~/display-bindings.md | 65 ++ .../Documentation~/enable-actions.md | 27 + .../generate-cs-api-from-actions | 62 ++ ...es.md => get-information-about-devices.md} | 0 .../group-binding-to-control-scheme.md | 5 + .../Documentation~/how-interactions-work.md | 72 ++ .../Documentation~/interactive-rebinding.md | 32 + .../Documentation~/load-actions-from-json.md | 12 + .../Documentation~/look-up-binding.md | 37 + .../Documentation~/noisy-controls.md | 0 .../Documentation~/optimize-controls.md | 49 + .../Documentation~/predefined-interactions.md | 124 +++ .../Documentation~/predefined-processors.md | 108 ++ .../Documentation~/processors-on-actions.md | 11 + .../Documentation~/processors-on-bindings.md | 17 + .../Documentation~/processors-on-controls.md | 39 + .../record-control-state-history.md | 56 + .../restore-original-bindings.md | 15 + .../save-and-load-rebindings.md | 16 + ...{SettingUpInput.md => setting-up-input.md} | 8 +- .../Documentation~/stand-alone-actions.md | 29 + .../Documentation~/synthetic-controls.md | 7 + .../Documentation~/using-interactions.md | 35 + .../Documentation~/using-processors.md | 21 + .../write-custom-interactions.md | 57 + .../Documentation~/write-custom-processors.md | 77 ++ 60 files changed, 2118 insertions(+), 2284 deletions(-) delete mode 100644 Packages/com.unity.inputsystem/Documentation~/ActionAssets.md delete mode 100644 Packages/com.unity.inputsystem/Documentation~/ActionBindings.md delete mode 100644 Packages/com.unity.inputsystem/Documentation~/CreateActions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/action-assets.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/action-bindings.md rename Packages/com.unity.inputsystem/Documentation~/{ActionProperties.md => action-properties.md} (100%) rename Packages/com.unity.inputsystem/Documentation~/{ActionsEditor.md => actions-editor.md} (96%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/api-overview.md rename Packages/com.unity.inputsystem/Documentation~/{AssignProjectWideActions.md => assign-project-wide-actions.md} (100%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/binding-initial-state-checks.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/binding-overrides.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/binding-resolution.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/changing-bindings.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/composite-bindings.md rename Packages/com.unity.inputsystem/Documentation~/{ConfigureActions.md => configure-action-properties.md} (93%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/control-actuation.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/control-hierarchies.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/control-paths.md rename Packages/com.unity.inputsystem/Documentation~/{ControlSchemes.md => control-schemes.md} (100%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/control-state.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/control-types.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/control-usages.md rename Packages/com.unity.inputsystem/Documentation~/{CreateActionAsset.md => create-action-asset.md} (100%) rename Packages/com.unity.inputsystem/Documentation~/{CreateActionMaps.md => create-action-maps.md} (100%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/create-actions-in-code.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/create-actions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/dealing-with-binding-conflicts.md rename Packages/com.unity.inputsystem/Documentation~/{DefaultActions.md => default-actions.md} (63%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/display-bindings.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/enable-actions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/generate-cs-api-from-actions rename Packages/com.unity.inputsystem/Documentation~/{GetInfoAboutDevices.md => get-information-about-devices.md} (100%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/group-binding-to-control-scheme.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/how-interactions-work.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/interactive-rebinding.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/load-actions-from-json.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/look-up-binding.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/noisy-controls.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/optimize-controls.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/predefined-interactions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/predefined-processors.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/processors-on-actions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/processors-on-bindings.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/processors-on-controls.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/record-control-state-history.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/restore-original-bindings.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/save-and-load-rebindings.md rename Packages/com.unity.inputsystem/Documentation~/{SettingUpInput.md => setting-up-input.md} (64%) create mode 100644 Packages/com.unity.inputsystem/Documentation~/stand-alone-actions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/synthetic-controls.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/using-interactions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/using-processors.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/write-custom-interactions.md create mode 100644 Packages/com.unity.inputsystem/Documentation~/write-custom-processors.md diff --git a/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md b/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md deleted file mode 100644 index 1e8207c5a1..0000000000 --- a/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -uid: input-system-action-assets ---- -# Input Action Assets - - -# Concept title - -First line: Summarize purpose of page in one sentence, starting with -an active verb. No links or formatting. - -One to three paragraphs: Introduce the key takeaways of the body content, in -order of appearance. No headings, images, or tables. - -Final paragraph (optional): Links to related documentation the user -might be looking for instead. - -## Descriptive heading - -Use descriptive headings to break up the content and make the page easy to -scan. Organize content logically and introduce ideas gradually. - -### Detailed heading - -Don't use headings below H3 level. - -## Additional resources - -- [Link](related-content-on-Unity-owned-platforms) -- [Link](related-content-on-Unity-owned-platforms) - --------------------------------------------- - - -- [Descriptive heading](#descriptive-heading) - - [Detailed heading](#detailed-heading) -- [Additional resources](#additional-resources) -- [Project-Wide Actions](#project-wide-actions) -- [Using Input Action Assets](#using-input-action-assets) -- [Type-safe C# API Generation](#type-safe-c-api-generation) - - [Auto-generating script code for Actions](#auto-generating-script-code-for-actions) - - [Using Action Assets with `PlayerInput`](#using-action-assets-with-playerinput) - - [Modifying Input Action Assets at runtime](#modifying-input-action-assets-at-runtime) - - [The Default Actions Asset](#the-default-actions-asset) - -The Input System stores your configuration of [Input Actions](Actions.md) and their associated [Bindings](ActionBindings.md), [Action Maps](ActionsEditor.html#configure-action-maps) and [Control Schemes](ActionBindings.md#control-schemes) in an [Action Asset](ActionAssets.md) file. - -While it's possible to have more than one Action Asset in a project, most projects only ever need a single Action Asset. - -These Assets have the `.inputactions` file extension and are stored in a plain JSON format. - -The input system creates an Action Asset when you set up the [default project-wide actions](ProjectWideActions.md), but you can also create new Action Assets directly in the Project window. - -For most common scenarios, you do not need to use more than one Input Action Asset. This is because an Action Asset can contain multiple [Action Maps](ActionsEditor.html#configure-action-maps), which each containing a set of actions relevant to the various parts of your project (such as UI navigation, gameplay, etc). - -## Project-Wide Actions - -The Input System's **project-wide actions** feature allows you to choose an individual Action Asset to be available project-wide, which means the actions within that asset are available more conveniently through the Input System API without needing to set up references to a specific asset. - -When you assign an Action Asset as project-wide, it also becomes automatically [preloaded](https://docs.unity3d.com/ScriptReference/PlayerSettings.GetPreloadedAssets.html) when your app starts up, and is kept available until it terminates. - -Unless you have specific project requirements that require more than one Action Asset, the recommended workflow is to use a single Action Asset assigned as the project-wide actions. - - - - -## Using Input Action Assets - - -## Type-safe C# API Generation - -Input Action Assets allow you to **generate a C# class** from your action definitions, which allow you to refer to your actions in a type-safe manner from code. This means you can avoid looking up your actions by string. - -### Auto-generating script code for Actions - -One of the most convenient ways to work with `.inputactions` Assets in scripts is to automatically generate a C# wrapper class for them. This removes the need to manually look up Actions and Action Maps using their names, and also provides an easier way to set up callbacks. - -To enable this option, tick the __Generate C# Class__ checkbox in the importer properties in the Inspector of the `.inputactions` Asset, then select __Apply__. - -![MyPlayerControls Importer Settings](Images/FireActionInputAssetInspector.png) - -You can optionally choose a path name, class name, and namespace for the generated script, or keep the default values. - -This generates a C# script that simplifies working with the Asset. - -```CSharp -using UnityEngine; -using UnityEngine.InputSystem; - -// IGameplayActions is an interface generated from the "gameplay" action map -// we added (note that if you called the action map differently, the name of -// the interface will be different). This was triggered by the "Generate Interfaces" -// checkbox. -public class MyPlayerScript : MonoBehaviour, IGameplayActions -{ - // MyPlayerControls is the C# class that Unity generated. - // It encapsulates the data from the .inputactions asset we created - // and automatically looks up all the maps and actions for us. - MyPlayerControls controls; - - public void OnEnable() - { - if (controls == null) - { - controls = new MyPlayerControls(); - // Tell the "gameplay" action map that we want to get told about - // when actions get triggered. - controls.gameplay.SetCallbacks(this); - } - controls.gameplay.Enable(); - } - - public void OnDisable() - { - controls.gameplay.Disable(); - } - - public void OnUse(InputAction.CallbackContext context) - { - // 'Use' code here. - } - - public void OnMove(InputAction.CallbackContext context) - { - // 'Move' code here. - } - -} -``` - ->__Note__: To regenerate the .cs file, right-click the .inputactions asset in the Project Browser and choose "Reimport". - -### Using Action Assets with `PlayerInput` - -The [Player Input](PlayerInput.md) component provides a convenient way to handle input for one or multiple players. You can assign your Action Asset to the Player Input component so that it can then automatically handle activating Action Maps and selecting Control Schemes for you. - -![PlayerInput](Images/PlayerInput.png) - -### Modifying Input Action Assets at runtime -There are several ways to modify an Input Action Asset at runtime. Any modifications that you make during Play mode to an Input Action Asset do not persist in the Input Action Asset after you exit Play mode. This means you can test your application in a realistic manner in the Editor without having to worry about inadvertently modifying the asset. For examples on how to modify an Input Action Asset, see the documentation on [Creating Actions in code](Actions.md#creating-actions-in-code) and [Changing Bindings](ActionBindings.md#changing-bindings). - - -### The Default Actions Asset - -An asset called `DefaultInputActions.inputactions` containing a default setup of Actions comes with the Input System Package. You can reference this asset directly in your projects like any other Unity asset. However, the asset is also available in code form through the [`DefaultInputActions`](../api/UnityEngine.InputSystem.DefaultInputActions.html) class. - -```CSharp -void Start() -{ - // Create an instance of the default actions. - var actions = new DefaultInputActions(); - actions.Player.Look.performed += OnLook; - actions.Player.Move.performed += OnMove; - actions.Enable(); -} -``` - -> __Note:__ This default actions asset is older than, and entirely separate from the [default project-wide actions](ProjectWideActions.md). It is a legacy asset that remains included in the package for backward compatibility. diff --git a/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md b/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md deleted file mode 100644 index 3960ed7817..0000000000 --- a/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md +++ /dev/null @@ -1,971 +0,0 @@ ---- -uid: input-system-action-bindings ---- -# Action Bindings - -- [Composite Bindings](#composite-bindings) - - [1D axis](#1d-axis) - - [2D vector](#2d-vector) - - [3D vector](#3d-vector) - - [One Modifier](#one-modifier) - - [Two Modifiers](#two-modifiers) - - [Writing custom Composites](#writing-custom-composites) -- [Working with Bindings](#working-with-bindings) -- [Looking up Bindings](#looking-up-bindings) -- [Changing Bindings](#changing-bindings) - - [Applying overrides](#applying-overrides) - - [Erasing Bindings](#erasing-bindings) - - [Adding Bindings](#adding-bindings) - - [Setting parameters](#setting-parameters) -- [Interactive rebinding](#interactive-rebinding) -- [Saving and loading rebinds](#saving-and-loading-rebinds) - - [Restoring original Bindings](#restoring-original-bindings) - - [Displaying Bindings](#displaying-bindings) -- [Control Schemes](#control-schemes) -- [Details](#details) - - [Binding resolution](#binding-resolution) - - [Conflicting inputs](#conflicting-inputs) - - [Initial state check](#initial-state-check) - - -### Bindings - -* To add a new Binding, select the Add (+) icon on the action you want to add it to, and select the binding type from the menu that appears. -* To delete an existing Binding, either right-click it and select __Delete__ from the context menu. -* To duplicate an existing Binding, either right-click it and select __Duplicate__ from the context menu. - -You can add multiple bindings to an action, which is generally useful for supporting multiple types of input device. For example, in the default set of actions, the "Move" action has a binding to the left gamepad stick and the WSAD keys, which means input through any of these bindings will perform the action. - -![The default "move" action with its multiple bindings highlighted](./Images/ActionWithMultipleBindings.png)
-_The default "Move" action in the Actions Editor window, displaying the multiple bindings associated with it._ - -If you select a Binding, you can edit its properties in the right-hand pane of the window: - -![Binding Properties](Images/BindingProperties.png) - - - - - -An [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html) represents a connection between an [Action](Actions.md) and one or more [Controls](Controls.md) identified by a [Control path](Controls.md#control-paths). For example, the **right trigger** of a gamepad (a control) might be bound to an an action named "accelerate", so that pulling the right trigger causes a car to accelerate in your game. - -You can add multiple bindings to an action, which is generally useful for supporting multiple types of input device. For example, in the default set of actions, the "Move" action has a binding to the left gamepad stick and the WSAD keys, which means input through any of these bindings will perform the action. - -You can also bind multiple controls from the same device to an action. For example, both the left and right trigger of a gamepad could be mapped to the same action, so that pulling either trigger has the same result in your game. - -![The default "move" action with its multiple bindings highlighted](./Images/ActionWithMultipleBindings.png)
-_The default "Move" action in the Actions Editor window, displaying the multiple bindings associated with it._ - - -Each Binding has the following properties: - -|Property|Description| -|--------|-----------| -|[`path`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_path)|[Control path](Controls.md#control-paths) that identifies the control(s) from which the Action should receive input.

Example: `"/leftStick"`| -|[`overridePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overridePath)|[Control path](Controls.md#control-paths) that overrides `path`. Unlike `path`, `overridePath` is not persistent, so you can use it to non-destructively override the path on a Binding. If it is set to something other than null, it takes effect and overrides `path`. To get the path which is currently in effect (that is, either `path` or `overridePath`), you can query the [`effectivePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_effectivePath) property.| -|[`action`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_action)|The name or ID of the Action that the Binding should trigger. Note that this can be null or empty (for instance, for [composites](#composite-bindings)). Not case-sensitive.

Example: `"fire"`| -|[`groups`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_groups)|A semicolon-separated list of Binding groups that the Binding belongs to. Can be null or empty. Binding groups can be anything, but are mostly used for [Control Schemes](#control-schemes). Not case-sensitive.

Example: `"Keyboard&Mouse;Gamepad"`| -|[`interactions`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_interactions)|A semicolon-separated list of [Interactions](Interactions.md) to apply to input on this Binding. Note that Unity appends Interactions applied to the [Action](Actions.md) itself (if any) to this list. Not case-sensitive.

Example: `"slowTap;hold(duration=0.75)"`| -|[`processors`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_processors)|A semicolon-separated list of [Processors](Processors.md) to apply to input on this Binding. Note that Unity appends Processors applied to the [Action](Actions.md) itself (if any) to this list. Not case-sensitive.

Processors on Bindings apply in addition to Processors on Controls that are providing values. For example, if you put a `stickDeadzone` Processor on a Binding and then bind it to `/leftStick`, you get deadzones applied twice: once from the deadzone Processor sitting on the `leftStick` Control, and once from the Binding.

Example: `"invert;axisDeadzone(min=0.1,max=0.95)"`| -|[`id`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_id)|Unique ID of the Binding. You can use it to identify the Binding when storing Binding overrides in user settings, for example.| -|[`name`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_name)|Optional name of the Binding. Identifies part names inside [Composites](#composite-bindings).

Example: `"Positive"`| -|[`isComposite`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_isComposite)|Whether the Binding acts as a [Composite](#composite-bindings).| -|[`isPartOfComposite`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_isPartOfComposite)|Whether the Binding is part of a [Composite](#composite-bindings).| - -To query the Bindings to a particular Action, you can use [`InputAction.bindings`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_bindings). To query a flat list of Bindings for all Actions in an Action Map, you can use [`InputActionMap.bindings`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_bindings). - -## Composite Bindings - -Sometimes, you might want to have several Controls act in unison to mimic a different type of Control. The most common example of this is using the W, A, S, and D keys on the keyboard to form a 2D vector Control equivalent to mouse deltas or gamepad sticks. Another example is to use two keys to form a 1D axis equivalent to a mouse scroll axis. - -This is difficult to implement with normal Bindings. You can bind a [`ButtonControl`](../api/UnityEngine.InputSystem.Controls.ButtonControl.html) to an action expecting a `Vector2`, but doing so results in an exception at runtime when the Input System tries to read a `Vector2` from a Control that can deliver only a `float`. - -Composite Bindings (that is, Bindings that are made up of other Bindings) solve this problem. Composites themselves don't bind directly to Controls; instead, they source values from other Bindings that do, and then synthesize input on the fly from those values. - -To see how to create Composites in the editor UI, see documentation on [editing Composite Bindings](ActionsEditor.md#editing-composite-bindings). - -To create composites in code, you can use the [`AddCompositeBinding`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.html#UnityEngine_InputSystem_InputActionSetupExtensions_AddCompositeBinding_UnityEngine_InputSystem_InputAction_System_String_System_String_System_String_) syntax. - -```CSharp -myAction.AddCompositeBinding("Axis") - .With("Positive", "/rightTrigger") - .With("Negative", "/leftTrigger"); -``` - -Each Composite consists of one Binding that has [`InputBinding.isComposite`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_isComposite) set to true, followed by one or more Bindings that have [`InputBinding.isPartOfComposiste`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_isPartOfComposite) set to true. In other words, several consecutive entries in [`InputActionMap.bindings`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_bindings) or [`InputAction.bindings`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_bindings) together form a Composite. - -Note that each composite part can be bound arbitrary many times. - -```CSharp -// Make both shoulders and triggers pull on the axis. -myAction.AddCompositeBinding("Axis") - .With("Positive", "/rightTrigger") - .With("Positive", "/rightShoulder") - .With("Negative", "/leftTrigger"); - .With("Negative", "/leftShoulder"); -``` - -Composites can have parameters, just like [Interactions](Interactions.md) and [Processors](Processors.md). - -```CSharp -myAction.AddCompositeBinding("Axis(whichSideWins=1)"); -``` - -There are currently five Composite types that come with the system out of the box: [1D-Axis](#1d-axis), [2D-Vector](#2d-vector), [3D-Vector](#3d-vector), [One Modifier](#one-modifier) and [Two Modifiers](#two-modifiers). Additionally, you can [add your own](#writing-custom-composites) types of Composites. - -### 1D axis - -![Add 1D Axis Composite](./Images/Add1DAxisComposite.png) - -![1D Axis Composite](./Images/1DAxisComposite.png) - -A Composite made of two buttons: one that pulls a 1D axis in its negative direction, and another that pulls it in its positive direction. Implemented in the [`AxisComposite`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html) class. The result is a `float`. - -```CSharp -myAction.AddCompositeBinding("1DAxis") // Or just "Axis" - .With("Positive", "/rightTrigger") - .With("Negative", "/leftTrigger"); -``` - -The axis Composite has two part bindings. - -|Part|Type|Description| -|----|----|-----------| -|[`positive`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_positive)|`Button`|Controls pulling in the positive direction (towards [`maxValue`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_maxValue)).| -|[`negative`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_negative)|`Button`|Controls pulling in the negative direction, (towards [`minValue`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_minValue)).| - -You can set the following parameters on an axis Composite: - -|Parameter|Description| -|---------|-----------| -|[`whichSideWins`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_whichSideWins)|What happens if both [`positive`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_positive) and [`negative`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_negative) are actuated. See table below.| -|[`minValue`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_minValue)|The value returned if the [`negative`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_negative) side is actuated. Default is -1.| -|[`maxValue`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_maxValue)|The value returned if the [`positive`](../api/UnityEngine.InputSystem.Composites.AxisComposite.html#UnityEngine_InputSystem_Composites_AxisComposite_positive) side is actuated. Default is 1.| - -If Controls from both the `positive` and the `negative` side are actuated, then the resulting value of the axis Composite depends on the `whichSideWin` parameter setting. - -|[`WhichSideWins`](../api/UnityEngine.InputSystem.Composites.AxisComposite.WhichSideWins.html)|Description| -|---------------|-----------| -|(0) `Neither`|Neither side has precedence. The Composite returns the midpoint between `minValue` and `maxValue` as a result. At their default settings, this is 0.

This is the default value for this setting.| -|(1) `Positive`|The positive side has precedence and the Composite returns `maxValue`.| -|(2) `Negative`|The negative side has precedence and the Composite returns `minValue`.| - ->__Note__: There is no support yet for interpolating between the positive and negative over time. - -### 2D vector - -![Add 2D Vector Composite](./Images/Add2DVectorComposite.png) - -![2D Vector Composite](./Images/2DVectorComposite.png) - -A Composite that represents a 4-way button setup like the D-pad on gamepads. Each button represents a cardinal direction. Implemented in the [`Vector2Composite`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html) class. The result is a `Vector2`. - -This Composite is most useful for representing up-down-left-right controls, such as WASD keyboard input. - -```CSharp -myAction.AddCompositeBinding("2DVector") // Or "Dpad" - .With("Up", "/w") - .With("Down", "/s") - .With("Left", "/a") - .With("Right", "/d"); - -// To set mode (2=analog, 1=digital, 0=digitalNormalized): -myAction.AddCompositeBinding("2DVector(mode=2)") - .With("Up", "/leftStick/up") - .With("Down", "/leftStick/down") - .With("Left", "/leftStick/left") - .With("Right", "/leftStick/right"); -``` - -The 2D vector Composite has four part Bindings. - -|Part|Type|Description| -|----|----|-----------| -|[`up`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_up)|`Button`|Controls representing `(0,1)` (+Y).| -|[`down`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_down)|`Button`|Controls representing `(0,-1)` (-Y).| -|[`left`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_left)|`Button`|Controls representing `(-1,0)` (-X).| -|[`right`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_right)|`Button`|Controls representing `(1,0)` (+X).| - -In addition, you can set the following parameters on a 2D vector Composite: - -|Parameter|Description| -|---------|-----------| -|[`mode`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_mode)|Whether to treat the inputs as digital or as analog controls.

If this is set to [`Mode.DigitalNormalized`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector2Composite_Mode_DigitalNormalized), inputs are treated as buttons (off if below [`defaultButtonPressPoint`](../api/UnityEngine.InputSystem.InputSettings.html#UnityEngine_InputSystem_InputSettings_defaultButtonPressPoint) and on if equal to or greater). Each input is 0 or 1 depending on whether the button is pressed or not. The vector resulting from the up/down/left/right parts is normalized. The result is a diamond-shaped 2D input range.

If this is set to [`Mode.Digital`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector2Composite_Mode_Digital), the behavior is essentially the same as [`Mode.DigitalNormalized`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector2Composite_Mode_DigitalNormalized) except that the resulting vector is not normalized.

Finally, if this is set to [`Mode.Analog`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector2Composite_Mode_Analog), inputs are treated as analog (i.e. full floating-point values) and, other than [`down`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_down) and [`left`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.html#UnityEngine_InputSystem_Composites_Vector2Composite_left) being inverted, values will be passed through as is.

The default is [`Mode.DigitalNormalized`](../api/UnityEngine.InputSystem.Composites.Vector2Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector2Composite_Mode_DigitalNormalized).| - ->__Note__: There is no support yet for interpolating between the up/down/left/right over time. - -### 3D vector - -![Add 3D Vector Composite](./Images/Add3DVectorComposite.png) - -![3D Vector Composite](./Images/3DVectorComposite.png) - -A Composite that represents a 6-way button where two combinations each control one axis of a 3D vector. Implemented in the [`Vector3Composite`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html) class. The result is a `Vector3`. - -```CSharp -myAction.AddCompositeBinding("3DVector") - .With("Up", "/w") - .With("Down", "/s") - .With("Left", "/a") - .With("Right", "/d"); - -// To set mode (2=analog, 1=digital, 0=digitalNormalized): -myAction.AddCompositeBinding("3DVector(mode=2)") - .With("Up", "/leftStick/up") - .With("Down", "/leftStick/down") - .With("Left", "/leftStick/left") - .With("Right", "/leftStick/right"); -``` - -The 3D vector Composite has four part Bindings. - -|Part|Type|Description| -|----|----|-----------| -|[`up`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_up)|`Button`|Controls representing `(0,1,0)` (+Y).| -|[`down`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_down)|`Button`|Controls representing `(0,-1,0)` (-Y).| -|[`left`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_left)|`Button`|Controls representing `(-1,0,0)` (-X).| -|[`right`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_right)|`Button`|Controls representing `(1,0,0)` (+X).| -|[`forward`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_forward)|`Button`|Controls representing `(0,0,1)` (+Z).| -|[`backward`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_backward)|`Button`|Controls representing `(0,0,-1)` (-Z).| - -In addition, you can set the following parameters on a 3D vector Composite: - -|Parameter|Description| -|---------|-----------| -|[`mode`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_mode)|Whether to treat the inputs as digital or as analog controls.

If this is set to [`Mode.DigitalNormalized`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector3Composite_Mode_DigitalNormalized), inputs are treated as buttons (off if below [`defaultButtonPressPoint`](../api/UnityEngine.InputSystem.InputSettings.html#UnityEngine_InputSystem_InputSettings_defaultButtonPressPoint) and on if equal to or greater). Each input is 0 or 1 depending on whether the button is pressed or not. The vector resulting from the up/down/left/right/forward/backward parts is normalized.

If this is set to [`Mode.Digital`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector3Composite_Mode_Digital), the behavior is essentially the same as [`Mode.DigitalNormalized`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector3Composite_Mode_DigitalNormalized) except that the resulting vector is not normalized.

Finally, if this is set to [`Mode.Analog`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector3Composite_Mode_Analog), inputs are treated as analog (that is, full floating-point values) and, other than [`down`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_down), [`left`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_left), and [`backward`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.html#UnityEngine_InputSystem_Composites_Vector3Composite_backward) being inverted, values will be passed through as they are.

The default is [`Analog`](../api/UnityEngine.InputSystem.Composites.Vector3Composite.Mode.html#UnityEngine_InputSystem_Composites_Vector3Composite_Mode_Analog).| - -### One Modifier - -![Add Binding With One Modifier](./Images/AddBindingWithOneModifier.png) - -![One Modifier Composite](./Images/OneModifierComposite.png) - -A Composite that requires the user to hold down a "modifier" button in addition to another control from which the actual value of the Binding is determined. This can be used, for example, for Bindings such as "SHIFT+1". Implemented in the [`OneModifierComposite`](../api/UnityEngine.InputSystem.Composites.OneModifierComposite.html) class. The buttons can be on any Device, and can be toggle buttons or full-range buttons such as gamepad triggers. - -The result is a value of the same type as the controls bound to the [`binding`](../api/UnityEngine.InputSystem.Composites.OneModifierComposite.html#UnityEngine_InputSystem_Composites_OneModifierComposite_binding) part. - -```CSharp -// Add binding for "CTRL+1". -myAction.AddCompositeBinding("OneModifier") - .With("Binding", "/1") - .With("Modifier", "/ctrl") - -// Add binding to mouse delta such that it only takes effect -// while the ALT key is down. -myAction.AddCompositeBinding("OneModifier") - .With("Binding", "/delta") - .With("Modifier", "/alt"); -``` - -The button with one modifier Composite has two part Bindings. - -|Part|Type|Description| -|----|----|-----------| -|[`modifier`](../api/UnityEngine.InputSystem.Composites.OneModifierComposite.html#UnityEngine_InputSystem_Composites_OneModifierComposite_modifier)|`Button`|Modifier that has to be held for `binding` to come through. If the user holds any of the buttons bound to the `modifier` at the same time as the button that triggers the action, the Composite assumes the value of the `modifier` Binding. If the user does not press any button bound to the `modifier`, the Composite remains at default value.| -|[`binding`](../api/UnityEngine.InputSystem.Composites.OneModifierComposite.html#UnityEngine_InputSystem_Composites_OneModifierComposite_binding)|Any|The control(s) whose value the Composite assumes while the user holds down the `modifier` button.| - -This Composite has no parameters. - -### Two Modifiers - -![Add Bindings With Two Modifiers](./Images/AddBindingWithTwoModifiers.png) - -![Two Modifiers Composite](./Images/TwoModifiersComposite.png) - -A Composite that requires the user to hold down two "modifier" buttons in addition to another control from which the actual value of the Binding is determined. This can be used, for example, for Bindings such as "SHIFT+CTRL+1". Implemented in the [`TwoModifiersComposite`](../api/UnityEngine.InputSystem.Composites.TwoModifiersComposite.html) class. The buttons can be on any Device, and can be toggle buttons or full-range buttons such as gamepad triggers. - -The result is a value of the same type as the controls bound to the [`binding`](../api/UnityEngine.InputSystem.Composites.TwoModifiersComposite.html#UnityEngine_InputSystem_Composites_TwoModifiersComposite_binding) part. - -```CSharp -myAction.AddCompositeBinding("TwoModifiers") - .With("Button", "/1") - .With("Modifier1", "/leftCtrl") - .With("Modifier1", "/rightCtrl") - .With("Modifier2", "/leftShift") - .With("Modifier2", "/rightShift"); -``` - -The button with two modifiers Composite has three part Bindings. - -|Part|Type|Description| -|----|----|-----------| -|[`modifier1`](../api/UnityEngine.InputSystem.Composites.TwoModifiersComposite.html#UnityEngine_InputSystem_Composites_TwoModifiersComposite_modifier1)|`Button`|The first modifier the user must hold alongside `modifier2`, for `binding` to come through. If the user does not press any button bound to the `modifier1`, the Composite remains at default value.| -|[`modifier2`](../api/UnityEngine.InputSystem.Composites.TwoModifiersComposite.html#UnityEngine_InputSystem_Composites_TwoModifiersComposite_modifier2)|`Button`|The second modifier the user must hold alongside `modifier1`, for `binding` to come through. If the user does not press any button bound to the `modifier2`, the Composite remains at default value.| -|[`binding`](../api/UnityEngine.InputSystem.Composites.TwoModifiersComposite.html#UnityEngine_InputSystem_Composites_TwoModifiersComposite_binding)|Any|The control(s) whose value the Composite assumes while the user presses both `modifier1` and `modifier2` at the same time.| - -This Composite has no parameters. - -### Writing custom Composites - -You can define new types of Composites, and register them with the API. Unity treats these the same as predefined types, which the Input System internally defines and registers in the same way. - -To define a new type of Composite, create a class based on [`InputBindingComposite`](../api/UnityEngine.InputSystem.InputBindingComposite-1.html). - -> __IMPORTANT__: Composites must be __stateless__. This means that you cannot store local state that changes depending on the input being processed. For __stateful__ processing on Bindings, see [interactions](./Interactions.md#writing-custom-interactions). - -```CSharp -// Use InputBindingComposite as a base class for a composite that returns -// values of type TValue. -// NOTE: It is possible to define a composite that returns different kinds of values -// but doing so requires deriving directly from InputBindingComposite. -#if UNITY_EDITOR -[InitializeOnLoad] // Automatically register in editor. -#endif -// Determine how GetBindingDisplayString() formats the composite by applying -// the DisplayStringFormat attribute. -[DisplayStringFormat("{firstPart}+{secondPart}")] -public class CustomComposite : InputBindingComposite -{ - // Each part binding is represented as a field of type int and annotated with - // InputControlAttribute. Setting "layout" restricts the controls that - // are made available for picking in the UI. - // - // On creation, the int value is set to an integer identifier for the binding - // part. This identifier can read values from InputBindingCompositeContext. - // See ReadValue() below. - [InputControl(layout = "Button")] - public int firstPart; - - [InputControl(layout = "Button")] - public int secondPart; - - // Any public field that is not annotated with InputControlAttribute is considered - // a parameter of the composite. This can be set graphically in the UI and also - // in the data (e.g. "custom(floatParameter=2.0)"). - public float floatParameter; - public bool boolParameter; - - // This method computes the resulting input value of the composite based - // on the input from its part bindings. - public override float ReadValue(ref InputBindingCompositeContext context) - { - var firstPartValue = context.ReadValue(firstPart); - var secondPartValue = context.ReadValue(secondPart); - - //... do some processing and return value - } - - // This method computes the current actuation of the binding as a whole. - public override float EvaluateMagnitude(ref InputBindingCompositeContext context) - { - // Compute normalized [0..1] magnitude value for current actuation level. - } - - static CustomComposite() - { - // Can give custom name or use default (type name with "Composite" clipped off). - // Same composite can be registered multiple times with different names to introduce - // aliases. - // - // NOTE: Registering from the static constructor using InitializeOnLoad and - // RuntimeInitializeOnLoadMethod is only one way. You can register the - // composite from wherever it works best for you. Note, however, that - // the registration has to take place before the composite is first used - // in a binding. Also, for the composite to show in the editor, it has - // to be registered from code that runs in edit mode. - InputSystem.RegisterBindingComposite(); - } - - [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] - static void Init() {} // Trigger static constructor. -} -``` - -The Composite should now appear in the editor UI when you add a Binding, and you can now use it in scripts. - -```CSharp - myAction.AddCompositeBinding("custom(floatParameter=2.0)") - .With("firstpart", "/buttonSouth") - .With("secondpart", "/buttonNorth"); -``` - -To define a custom parameter editor for the Composite, you can derive from [`InputParameterEditor`](../api/UnityEngine.InputSystem.Editor.InputParameterEditor-1.html). - -```CSharp -#if UNITY_EDITOR -public class CustomParameterEditor : InputParameterEditor -{ - public override void OnGUI() - { - EditorGUILayout.Label("Custom stuff"); - target.floatParameter = EditorGUILayout.FloatField("Some Parameter", target.floatParameter); - } -} -#endif -``` - -## Working with Bindings - -## Looking up Bindings - -You can retrieve the bindings of an action using its [`InputAction.bindings`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_bindings) property which returns a read-only array of [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html) structs. - -```CSharp - // Get bindings of "fire" action. - var fireBindings = playerInput.actions["fire"].bindings; -``` - -Also, all the bindings for all actions in an [`InputActionMap`](../api/UnityEngine.InputSystem.InputActionMap.html) are made available through the [`InputActionMap.bindings`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_bindings) property. The bindings are associated with actions through an [action ID](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_id) or [action name](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_name) stored in the [`InputBinding.action`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_action) property. - -```CSharp - // Get all bindings in "gameplay" action map. - var gameplayBindings = playerInput.actions.FindActionMap("gameplay").bindings; -``` - -You can also look up specific the indices of specific bindings in [`InputAction.bindings`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_bindings) using the [`InputActionRebindingExtensions.GetBindingIndex`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_GetBindingIndex_UnityEngine_InputSystem_InputAction_UnityEngine_InputSystem_InputBinding_) method. - -```CSharp - // Find the binding in the "Keyboard" control scheme. - playerInput.actions["fire"].GetBindingIndex(group: "Keyboard"); - - // Find the first binding to the space key in the "gameplay" action map. - playerInput.FindActionMap("gameplay").GetBindingIndex( - new InputBinding { path = "/space" }); -``` - -Finally, you can look up the binding that corresponds to a specific control through [`GetBindingIndexForControl`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_GetBindingIndexForControl_). This way, you can, for example, map a control found in the [`controls`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_controls) array of an [`InputAction`](../api/UnityEngine.InputSystem.InputAction.html) back to an [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html). - -```CSharp - // Find the binding that binds LMB to "fire". If there is no such binding, - // bindingIndex will be -1. - var fireAction = playerInput.actions["fire"]; - var bindingIndex = fireAction.GetBindingIndexForControl(Mouse.current.leftButton); - if (binding == -1) - Debug.Log("Fire is not bound to LMB of the current mouse."); -``` - -## Changing Bindings - -In general, you can change existing bindings via the [`InputActionSetupExtensions.ChangeBinding`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.html#UnityEngine_InputSystem_InputActionSetupExtensions_ChangeBinding_UnityEngine_InputSystem_InputAction_System_Int32_) method. This returns an accessor that can be used to modify the properties of the targeted [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html). Note that most of the write operations of the accessor are destructive. For non-destructive changes to bindings, see [Applying Overrides](#applying-overrides). - -```CSharp -// Get write access to the second binding of the 'fire' action. -var accessor = playerInput.actions['fire'].ChangeBinding(1); - -// You can also gain access through the InputActionMap. Each -// map contains an array of all its bindings (see InputActionMap.bindings). -// Here we gain access to the third binding in the map. -accessor = playerInput.actions.FindActionMap("gameplay").ChangeBinding(2); -``` - -You can use the resulting accessor to modify properties through methods such as [`WithPath`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.BindingSyntax.html#UnityEngine_InputSystem_InputActionSetupExtensions_BindingSyntax_WithPath_) or [`WithProcessors`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.BindingSyntax.html#UnityEngine_InputSystem_InputActionSetupExtensions_BindingSyntax_WithProcessors_). - -```CSharp -playerInput.actions["fire"].ChangeBinding(1) - // Change path to space key. - .WithPath("/space"); -``` - -You can also use the accessor to iterate through bindings using [`PreviousBinding`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.BindingSyntax.html#UnityEngine_InputSystem_InputActionSetupExtensions_BindingSyntax_PreviousBinding_) and [`NextBinding`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.BindingSyntax.html#UnityEngine_InputSystem_InputActionSetupExtensions_BindingSyntax_NextBinding_). - -```CSharp -// Move accessor to previous binding. -accessor = accessor.PreviousBinding(); - -// Move accessor to next binding. -accessor = accessor.NextBinding(); -``` - -If the given binding is a [composite](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_isComposite), you can address it by its name rather than by index. - -```CSharp -// Change the 2DVector composite of the "move" action. -playerInput.actions["move"].ChangeCompositeBinding("2DVector") - - -// -playerInput.actions["move"].ChangeBinding("WASD") -``` - -### Applying overrides - -You can override aspects of any Binding at run-time non-destructively. Specific properties of [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html) have an `override` variant that, if set, will take precedent over the property that they shadow. All `override` properties are of type `String`. - -|Property|Override|Description| -|--------|--------|-----------| -|[`path`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_path)|[`overridePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overridePath)|Replaces the [Control path](./Controls.md#control-paths) that determines which Control(s) are referenced in the binding. If [`overridePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overridePath) is set to an empty string, the binding is effectively disabled.

Example: `"/leftStick"`| -|[`processors`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_processors)|[`overrideProcessors`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overrideProcessors)|Replaces the [processors](./Processors.md) applied to the binding.

Example: `"invert,normalize(min=0,max=10)"`| -|[`interactions`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_interactions)|[`overrideInteractions`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overrideInteractions)|Replaces the [interactions](./Interactions.md) applied to the binding.

Example: `"tap(duration=0.5)"`| - ->NOTE: The `override` property values will not be saved along with the Actions (for example, when calling [`InputActionAsset.ToJson()`](../api/UnityEngine.InputSystem.InputActionAsset.html#UnityEngine_InputSystem_InputActionAsset_ToJson)). See [Saving and loading rebinds](#saving-and-loading-rebinds) for details about how to persist user rebinds. - -To set the various `override` properties, you can use the [`ApplyBindingOverride`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_ApplyBindingOverride_UnityEngine_InputSystem_InputAction_UnityEngine_InputSystem_InputBinding_) APIs. - -```CSharp -// Rebind the "fire" action to the left trigger on the gamepad. -playerInput.actions["fire"].ApplyBindingOverride("/leftTrigger"); -``` - -In most cases, it is best to locate specific bindings using APIs such as [`GetBindingIndexForControl`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_GetBindingIndexForControl_) and to then apply the override to that specific binding. - -```CSharp -// Find the "Jump" binding for the space key. -var jumpAction = playerInput.actions["Jump"]; -var bindingIndex = jumpAction.GetBindingIndexForControl(Keyboard.current.spaceKey); - -// And change it to the enter key. -jumpAction.ApplyBindingOverride(bindingIndex, "/enter"); -``` - -### Erasing Bindings - -You can erase a binding by calling [`Erase`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.BindingSyntax.html#UnityEngine_InputSystem_InputActionSetupExtensions_BindingSyntax_Erase_) on the [binding accessor](../api/UnityEngine.InputSystem.InputActionSetupExtensions.BindingSyntax.html). - -```CSharp -// Erase first binding on "fire" action. -playerInput.actions["fire"].ChangeBinding(0).Erase(); - -// Erase "2DVector" composite. This will also erase the part -// bindings of the composite. -playerInput.actions["move"].ChangeCompositeBinding("2DVector").Erase(); - -// Can also do this by using the name given to the composite binding. -playerInput.actions["move"].ChangeCompositeBinding("WASD").Erase(); - -// Erase first binding in "gameplay" action map. -playerInput.actions.FindActionMap("gameplay").ChangeBinding(0).Erase(); -``` - -### Adding Bindings - -New bindings can be added to an Action using [`AddAction`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.html#UnityEngine_InputSystem_InputActionSetupExtensions_AddBinding_UnityEngine_InputSystem_InputAction_System_String_System_String_System_String_System_String_) or [`AddCompositeBinding`](../api/UnityEngine.InputSystem.InputActionSetupExtensions.html#UnityEngine_InputSystem_InputActionSetupExtensions_AddCompositeBinding_UnityEngine_InputSystem_InputAction_System_String_System_String_System_String_). - -```CSharp -// Add a binding for the left mouse button to the "fire" action. -playerInput.actions["fire"].AddBinding("/leftButton"); - -// Add a WASD composite binding to the "move" action. -playerInput.actions["move"] - .AddCompositeBinding("2DVector") - .With("Up", "/w") - .With("Left", "/a") - .With("Down", "/s") - .With("Right", "/d"); -``` - -### Setting parameters - -A Binding may, either through itself or through its associated Action, lead to [processor](Processors.md), [interaction](Interactions.md), and/or [composite](#composite-bindings) objects being created. These objects can have parameters you can configure through in the [Binding properties view](ActionsEditor.md#bindings) of the Action editor or through the API. This configuration will give parameters their default value. - -```CSharp -// Create an action with a "Hold" interaction on it. -// Set the "duration" parameter to 4 seconds. -var action = new InputAction(interactions: "hold(duration=4)"); -``` - -You can query the current value of any such parameter using the [`GetParameterValue`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_GetParameterValue_UnityEngine_InputSystem_InputAction_System_String_UnityEngine_InputSystem_InputBinding_) API. - -```CSharp -// This returns a PrimitiveValue?. It will be null if the -// parameter is not found. Otherwise, it is a PrimitiveValue -// which can be converted to a number or boolean. -var p = action.GetParameterValue("duration"); -Debug.Log("'duration' is set to: " + p.Value); -``` - -The above looks for the parameter on any object found on any of the bindings on the action. You can restrict either or both to a more narrow set. - -```CSharp -// Retrieve the value of the "duration" parameter specifically of a -// "Hold" interaction and only look on bindings in the "Gamepad" group. -action.GetParameterValue("hold:duration", InputBinding.MaskByGroup("Gamepad")); -``` - -Alternatively, you can use an expression parameter to encapsulate both the type and the name of the parameter you want to get the value of. This has the advantage of not needing a string parameter but rather references both the type and the name of the parameter in a typesafe way. - -```CSharp -// Retrieve the value of the "duration" parameter of TapInteraction. -// This version returns a float? instead of a PrimitiveValue? as it -// sees the type of "duration" at compile-time. -action.GetParameterValue((TapInteraction x) => x.duration); -``` - -To alter the current value of a parameter, you can use what is referred to as a "parameter override". You can apply these at the level of an individual [`InputAction`](../api/UnityEngine.InputSystem.InputAction.html), or at the level of an entire [`InputActionMap`](../api/UnityEngine.InputSystem.InputActionMap.html), or even at the level of an entire [`InputActionAsset`](../api/UnityEngine.InputSystem.InputActionAsset.html). Such overrides are stored internally and applied automatically even on bindings added later. - -To add an override, use the [`ApplyParameterOverride`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_ApplyParameterOverride_UnityEngine_InputSystem_InputAction_System_String_UnityEngine_InputSystem_Utilities_PrimitiveValue_UnityEngine_InputSystem_InputBinding_) API or any of its overloads. - -```CSharp -// Set the "duration" parameter on all bindings of the action to 4. -action.ApplyParameterOverride("duration", 4f); - -// Set the "duration" parameter specifically for "tap" interactions only. -action.ApplyParameterOverride("tap:duration", 0.5f); - -// Set the "duration" parameter on tap interactions but only for bindings -// in the "Gamepad" group. -action.ApplyParameterOverride("tap:duration", 0.5f, InputBinding.MaskByGroup("Gamepad"); - -// Set tap duration for all bindings in an action map. -map.ApplyParameterOverride("tap:duration", 0.5f); - -// Set tap duration for all bindings in an entire asset. -asset.ApplyParameterOverride("tap:duration", 0.5f); - -// Like for GetParameterValue, overloads are available that take -// an expression instead. -action.ApplyParameterOverride((TapInteraction x) => x.duration, 0.4f); -map.ApplyParameterOverride((TapInteraction x) => x.duration, 0.4f); -asset.ApplyParameterOverride((TapInteraction x) => x.duration, 0.4f); -``` - -The new value will be applied immediately and affect all composites, processors, and interactions already in use and targeted by the override. - -Note that if multiple parameter overrides are applied – especially when applying some directly to actions and some to maps or assets –, there may be conflicts between which override to apply. In this case, an attempt is made to chose the "most specific" override to apply. - -```CSharp -// Let's say you have an InputAction `action` that is part of an InputActionAsset asset. -var map = action.actionMap; -var asset = map.asset; - -// And you apply a "tap:duration" override to the action. -action.ApplyParameterOverride("tap:duration", 0.6f); - -// But also apply a "tap:duration" override to the action specifically -// for bindings in the "Gamepad" group. -action.ApplyParameterOverride("tap:duration", 1f, InputBinding.MaskByGroup("Gamepad")); - -// And finally also apply a "tap:duration" override to the entire asset. -asset.ApplyParameterOverride("tap:duration", 0.3f); - -// Now, bindings on `action` in the "Gamepad" group will use a value of 1 for tap durations, -// other bindings on `action` will use 0.6, and every other binding in the asset will use 0.3. -``` - -You can use parameter overrides, for example, to scale mouse delta values on a "Look" action. - -```CSharp -// Set up an example "Look" action. -var look = new InputAction("look", type: InputActionType.Value); -look.AddBinding("/delta", groups: "KeyboardMouse", processors: "scaleVector2"); -look.AddBinding("/rightStick", groups: "Gamepad", processors: "scaleVector2"); - -// Now you can adjust stick sensitivity separately from mouse sensitivity. -look.ApplyParameterOverride("scaleVector2:x", 0.5f, InputBinding.MaskByGroup("KeyboardMouse")); -look.ApplyParameterOverride("scaleVector2:y", 0.5f, InputBinding.MaskByGroup("KeyboardMouse")); - -look.ApplyParameterOverride("scaleVector2:x", 2f, InputBinding.MaskByGroup("Gamepad")); -look.ApplyParameterOverride("scaleVector2:y", 2f, InputBinding.MaskByGroup("Gamepad")); - -// Alternative to using groups, you can also apply overrides directly to specific binding paths. -look.ApplyParameterOverride("scaleVector2:x", 0.5f, new InputBinding("/delta")); -look.ApplyParameterOverride("scaleVector2:y", 0.5f, new InputBinding("/delta")); -``` - ->NOTE: Parameter overrides are *not* persisted along with an asset. - -## Interactive rebinding - ->__Note:__ To download a sample project which demonstrates how to set up a rebinding user interface with Input System APIs, open the Package Manager, select the Input System Package, and choose the sample project "Rebinding UI" to download. - -Runtime rebinding allows users of your application to set their own Bindings. - -To allow users to choose their own Bindings interactively, use the [`InputActionRebindingExtensions.RebindingOperation`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html) class. Call the [`PerformInteractiveRebinding()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_PerformInteractiveRebinding_UnityEngine_InputSystem_InputAction_System_Int32_) method on an Action to create a rebinding operation. This operation waits for the Input System to register any input from any Device which matches the Action's expected Control type, then uses [`InputBinding.overridePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overridePath) to assign the Control path for that Control to the Action's Bindings. If the user actuates multiple Controls, the rebinding operation chooses the Control with the highest [magnitude](Controls.md#control-actuation). - ->IMPORTANT: You must dispose of [`InputActionRebindingExtensions.RebindingOperation`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html) instances via `Dispose()`, so that they don't leak memory on the unmanaged memory heap. - -```C# - void RemapButtonClicked(InputAction actionToRebind) - { - var rebindOperation = actionToRebind - .PerformInteractiveRebinding().Start(); - } -``` - -The [`InputActionRebindingExtensions.RebindingOperation`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html) API is highly configurable to match your needs. For example, you can: - -* Choose expected Control types ([`WithExpectedControlType()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RebindingOperation_WithExpectedControlType_System_Type_)). - -* Exclude certain Controls ([`WithControlsExcluding()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RebindingOperation_WithControlsExcluding_System_String_)). - -* Set a Control to cancel the operation ([`WithCancelingThrough()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RebindingOperation_WithCancelingThrough_UnityEngine_InputSystem_InputControl_)). - -* Choose which Bindings to apply the operation on if the Action has multiple Bindings ([`WithTargetBinding()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RebindingOperation_WithTargetBinding_System_Int32_), [`WithBindingGroup()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RebindingOperation_WithBindingGroup_System_String_), [`WithBindingMask()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RebindingOperation_WithBindingMask_System_Nullable_UnityEngine_InputSystem_InputBinding__)). - -Refer to the scripting API reference for [`InputActionRebindingExtensions.RebindingOperation`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.RebindingOperation.html) for a full overview. - -Note that [`PerformInteractiveRebinding()`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_PerformInteractiveRebinding_UnityEngine_InputSystem_InputAction_System_Int32_) automatically applies a set of default configurations based on the given action and targeted binding. - -## Saving and loading rebinds - -You can serialize override properties of [Bindings](../api/UnityEngine.InputSystem.InputBinding.html) by serializing them as JSON strings and restoring them from these. Use [`SaveBindingOverridesAsJson`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_SaveBindingOverridesAsJson_UnityEngine_InputSystem_IInputActionCollection2_) to create these strings and [`LoadBindingOverridesFromJson`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_LoadBindingOverridesFromJson_UnityEngine_InputSystem_IInputActionCollection2_System_String_System_Boolean_) to restore overrides from them. - -```CSharp -// Store player rebinds in PlayerPrefs. -var rebinds = playerInput.actions.SaveBindingOverridesAsJson(); -PlayerPrefs.SetString("rebinds", rebinds); - -// Restore player rebinds from PlayerPrefs (removes all existing -// overrides on the actions; pass `false` for second argument -// in case you want to prevent that). -var rebinds = PlayerPrefs.GetString("rebinds"); -playerInput.actions.LoadBindingOverridesFromJson(rebinds); -``` - -### Restoring original Bindings - -You can remove Binding overrides and thus restore defaults by using [`RemoveBindingOverride`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RemoveBindingOverride_UnityEngine_InputSystem_InputAction_System_Int32_) or [`RemoveAllBindingOverrides`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_RemoveAllBindingOverrides_UnityEngine_InputSystem_IInputActionCollection2_). - -```CSharp -// Remove binding overrides from the first binding of the "fire" action. -playerInput.actions["fire"].RemoveBindingOverride(0); - -// Remove all binding overrides from the "fire" action. -playerInput.actions["fire"].RemoveAllBindingOverrides(); - -// Remove all binding overrides from a player's actions. -playerInput.actions.RemoveAllBindingOverrides(); -``` - -### Displaying Bindings - -It can be useful for the user to know what an Action is currently bound to (taking any potentially active rebindings into account) while rebinding UIs, and for on-screen hints while the app is running. You can use [`InputBinding.effectivePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_effectivePath) to get the currently active path for a Binding (which returns [`overridePath`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_overridePath) if set, or otherwise returns [`path`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_path)). - -The easiest way to retrieve a display string for an action is to call [`InputActionRebindingExtensions.GetBindingDisplayString`](../api/UnityEngine.InputSystem.InputActionRebindingExtensions.html#UnityEngine_InputSystem_InputActionRebindingExtensions_GetBindingDisplayString_) which is an extension method for [`InputAction`](../api/UnityEngine.InputSystem.InputAction.html). - -```CSharp - // Get a binding string for the action as a whole. This takes into account which - // bindings are currently active and the actual controls bound to the action. - m_RebindButton.GetComponentInChildren().text = action.GetBindingDisplayString(); - - // Get a binding string for a specific binding on an action by index. - m_RebindButton.GetComponentInChildren().text = action.GetBindingDisplayString(1); - - // Look up binding indices with GetBindingIndex. - var bindingIndex = action.GetBindingIndex(InputBinding.MaskByGroup("Gamepad")); - m_RebindButton.GetComponentInChildren().text = - action.GetBindingDisplayString(bindingIndex); -``` - -You can also use this method to replace the text string with images. - -```CSharp - // Call GetBindingDisplayString() such that it also returns information about the - // name of the device layout and path of the control on the device. This information - // is useful for reliably associating imagery with individual controls. - // NOTE: The first argument is the index of the binding within InputAction.bindings. - var bindingString = action.GetBindingDisplayString(0, out deviceLayout, out controlPath); - - // If it's a gamepad, look up an icon for the control. - Sprite icon = null; - if (!string.IsNullOrEmpty(deviceLayout) - && !string.IsNullOrEmpty(controlPath) - && InputSystem.IsFirstLayoutBasedOnSecond(deviceLayout, "Gamepad")) - { - switch (controlPath) - { - case "buttonSouth": icon = aButtonIcon; break; - case "dpad/up": icon = dpadUpIcon; break; - //... - } - } - - // If you have an icon, display it instead of the text. - var text = m_RebindButton.GetComponentInChildren(); - var image = m_RebindButton.GetComponentInChildren(); - if (icon != null) - { - // Display icon. - text.gameObject.SetActive(false); - image.gameObject.SetActive(true); - image.sprite = icon; - } - else - { - // Display text. - text.gameObject.SetActive(true); - image.gameObject.SetActive(false); - text.text = bindingString; - } -``` - -Additionally, each Binding has a [`ToDisplayString`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_ToDisplayString_UnityEngine_InputSystem_InputBinding_DisplayStringOptions_UnityEngine_InputSystem_InputControl_) method, which you can use to turn individual Bindings into display strings. There is also a generic formatting method for Control paths, [`InputControlPath.ToHumanReadableString`](../api/UnityEngine.InputSystem.InputControlPath.html#UnityEngine_InputSystem_InputControlPath_ToHumanReadableString_System_String_UnityEngine_InputSystem_InputControlPath_HumanReadableStringOptions_UnityEngine_InputSystem_InputControl_), which you can use with arbitrary Control path strings. - -Note that the Controls a Binding resolves to can change at any time, and the display strings for controls might change dynamically. For example, if the user switches the currently active keyboard layout, the display string for each individual key on the [`Keyboard`](../api/UnityEngine.InputSystem.Keyboard.html) might change. - -## Control Schemes - -A Binding can belong to any number of Binding groups. Unity stores these on the [`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html) class as a semicolon-separated string in the [`InputBinding.groups`](../api/UnityEngine.InputSystem.InputBinding.html#UnityEngine_InputSystem_InputBinding_groups) property, and you can use them for any arbitrary grouping of bindings. To enable different sets of binding groups for an [`InputActionMap`](../api/UnityEngine.InputSystem.InputActionMap.html) or [`InputActionAsset`](../api/UnityEngine.InputSystem.InputActionAsset.html), you can use the [`InputActionMap.bindingMask`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_bindingMask)/[`InputActionAsset.bindingMask`](../api/UnityEngine.InputSystem.InputActionAsset.html#UnityEngine_InputSystem_InputActionAsset_bindingMask) property. The Input System uses this to implement the concept of grouping Bindings into different [`InputControlSchemes`](../api/UnityEngine.InputSystem.InputControlScheme.html). - -Control Schemes use Binding groups to map Bindings in an [`InputActionMap`](../api/UnityEngine.InputSystem.InputActionMap.html) or [`InputActionAsset`](../api/UnityEngine.InputSystem.InputActionAsset.html) to different types of Devices. The [`PlayerInput`](PlayerInput.md) class uses these to enable a matching Control Scheme for a new [user](UserManagement.md) joining the game, based on the Device they are playing on. - -## Details - -### Binding resolution - -When the Input System accesses the [Controls](Controls.md) bound to an Action for the first time, the Action resolves its Bindings to match them to existing Controls on existing Devices. In this process, the Action calls [`InputSystem.FindControls<>()`](../api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_FindControls__1_System_String_UnityEngine_InputSystem_InputControlList___0___) (filtering for devices assigned to the InputActionMap, if there are any) for the Binding path of each of the Action's bindings. This creates a list of resolved Controls that are now bound to the Action. - -Note that a single [Binding path](Controls.md#control-paths) can match multiple Controls: - -* A specific Device path such as `/buttonEast` matches the "Circle" button on a [PlayStation controller](Gamepad.md#playstation-controllers). If you have multiple PlayStation controllers connected, it resolves to the "Circle" button on each of these controllers. - -* An abstract Device path such as `/buttonEast` matches the right action button on any connected gamepad. If you have a PlayStation controller and an [Xbox controller](Gamepad.md#xbox-controllers) connected, it resolves to the "Circle" button on the PlayStation controller, and to the "B" button on the Xbox controller. - -* A Binding path can also contain wildcards, such as `/button*`. This matches any Control on any gamepad with a name starting with "button", which matches all the four action buttons on any connected gamepad. A different example: `*/{Submit}` matches any Control tagged with the "Submit" [usage](Controls.md#control-usages) on any Device. - -If there are multiple Bindings on the same Action that all reference the same Control(s), the Control will effectively feed into the Action multiple times. This is to allow, for example, a single Control to produce different input on the same Action by virtue of being bound in a different fashion (composites, processors, interactions, etc). However, regardless of how many times a Control is bound on any given action, it will only be mentioned once in the Action's [array of `controls`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_controls). - -To query the Controls that an Action resolves to, you can use [`InputAction.controls`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_controls). You can also run this query if the Action is disabled. - -To be notified when binding resolution happens, you can listen to [`InputSystem.onActionChange`](../api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_onActionChange) which triggers [`InputActionChange.BoundControlsAboutToChange`](../api/UnityEngine.InputSystem.InputActionChange.html#UnityEngine_InputSystem_InputActionChange_BoundControlsAboutToChange) before modifying Control lists and triggers [`InputActionChange.BoundControlsChanged`](../api/UnityEngine.InputSystem.InputActionChange.html#UnityEngine_InputSystem_InputActionChange_BoundControlsChanged) after having updated them. - -#### Binding resolution while Actions are enabled - -In certain situations, the [Controls](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_controls) bound to an Action have to be updated more than once. For example, if a new [Device](Devices.md) becomes usable with an Action, the Action may now pick up input from additional controls. Also, if Bindings are added, removed, or modified, Control lists will need to be updated. - -This updating of Controls usually happens transparently in the background. However, when an Action is [enabled](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_enabled) and especially when it is [in progress](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_IsInProgress_), there may be a noticeable effect on the Action. - -Adding or removing a device – either [globally](../api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_devices) or to/from the [device list](../api/UnityEngine.InputSystem.InputActionAsset.html#UnityEngine_InputSystem_InputActionAsset_devices) of an Action – will remain transparent __except__ if an Action is in progress and it is the device of its [active Control](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_activeControl) that is being removed. In this case, the Action will automatically be [cancelled](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_canceled). - -Modifying the [binding mask](../api/UnityEngine.InputSystem.InputActionAsset.html#UnityEngine_InputSystem_InputActionAsset_bindingMask) or modifying any of the Bindings (such as through [rebinding](#interactive-rebinding) or by adding or removing bindings) will, however, lead to all enabled Actions being temporarily disabled and then re-enabled and resumed. - -#### Choosing which Devices to use - ->__Note__: [`InputUser`](UserManagement.md) and [`PlayerInput`](PlayerInput.md) make use of this facility automatically. They set [`InputActionMap.devices`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_devices) automatically based on the Devices that are paired to the user. - -By default, Actions resolve their Bindings against all Devices present in the Input System (that is, [`InputSystem.devices`](../api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_devices)). For example, if there are two gamepads present in the system, a Binding to `/buttonSouth` picks up both gamepads and allows the Action to be used from either. - -You can override this behavior by restricting [`InputActionAssets`](../api/UnityEngine.InputSystem.InputActionAsset.html) or individual [`InputActionMaps`](../api/UnityEngine.InputSystem.InputActionMap.html) to a specific set of Devices. If you do this, Binding resolution only takes the Controls of the given Devices into account. - -``` - var actionMap = new InputActionMap(); - - // Restrict the action map to just the first gamepad. - actionMap.devices = new[] { Gamepad.all[0] }; -``` - -### Conflicting inputs - -There are two situations where a given input may lead to ambiguity: - -1. Several Controls are bound to the same Action and more than one is feeding input into the Action at the same time. Example: an Action that is bound to both the left and right trigger on a Gamepad and both triggers are pressed. -2. The input is part of a sequence of inputs and there are several possible such sequences. Example: one Action is bound to the `B` key and another Action is bound to `Shift-B`. - -#### Multiple, concurrently used Controls - ->__Note:__ This section does not apply to [`PassThrough`](RespondingToActions.md#pass-through) Actions as they are by design meant to allow multiple concurrent inputs. - -For a [`Button`](RespondingToActions.md#button) or [`Value`](RespondingToActions.md#value) Action, there can only be one Control at any time that is "driving" the Action. This Control is considered the [`activeControl`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_activeControl). - -When an Action is bound to multiple Controls, the [`activeControl`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_activeControl) at any point is the one with the greatest level of ["actuation"](Controls.md#control-actuation), that is, the largest value returned from [`EvaluateMagnitude`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_EvaluateMagnitude_). If a Control exceeds the actuation level of the current [`activeControl`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_activeControl), it will itself become the active Control. - -The following example demonstrates this mechanism with a [`Button`](RespondingToActions.md#button) Action and also demonstrates the difference to a [`PassThrough`](RespondingToActions.md#pass-through) Action. - -```CSharp -// Create a button and a pass-through action and bind each of them -// to both triggers on the gamepad. -var buttonAction = new InputAction(type: InputActionType.Button, - binding: "/*Trigger"); -var passThroughAction = new InputAction(type: InputActionType.PassThrough, - binding: "/*Trigger"); - -buttonAction.performed += c => Debug.Log("${c.control.name} pressed (Button)"); -passThroughAction.performed += c => Debug.Log("${c.control.name} changed (Pass-Through)"); - -buttonAction.Enable(); -passThroughAction.Enable(); - -// Press the left trigger all the way down. -// This will trigger both buttonAction and passThroughAction. Both will -// see leftTrigger becoming the activeControl. -Set(gamepad.leftTrigger, 1f); - -// Will log -// "leftTrigger pressed (Button)" and -// "leftTrigger changed (Pass-Through)" - -// Press the right trigger halfway down. -// This will *not* trigger or otherwise change buttonAction as the right trigger -// is actuated *less* than the left one that is already driving action. -// However, passThrough action is not performing such tracking and will thus respond -// directly to the value change. It will perform and make rightTrigger its activeControl. -Set(gamepad.rightTrigger, 0.5f); - -// Will log -// "rightTrigger changed (Pass-Through)" - -// Release the left trigger. -// For buttonAction, this will mean that now all controls feeding into the action have -// been released and thus the button releases. activeControl will go back to null. -// For passThrough action, this is just another value change. So, the action performs -// and its active control changes to leftTrigger. -Set(gamepad.leftTrigger, 0f); - -// Will log -// "leftTrigger changed (Pass-Through)" -``` - -For [composite bindings](#composite-bindings), magnitudes of the composite as a whole rather than for individual Controls are tracked. However, [`activeControl`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_activeControl) will stick track individual Controls from the composite. - -##### Disabling Conflict Resolution - -Conflict resolution is always applied to [Button](RespondingToActions.md#button) and [Value](RespondingToActions.md#value) type Actions. However, it can be undesirable in situations when an Action is simply used to gather any and all inputs from bound Controls. For example, the following Action would monitor the A button of all available gamepads: - -```CSharp -var action = new InputAction(type: InputActionType.PassThrough, binding: "/buttonSouth"); -action.Enable(); -``` - -By using the [Pass-Through](RespondingToActions.md#pass-through) Action type, conflict resolution is bypassed and thus, pressing the A button on one gamepad will not result in a press on a different gamepad being ignored. - -#### Multiple input sequences (such as keyboard shortcuts) - ->__Note__: The mechanism described here only applies to Actions that are part of the same [`InputActionMap`](../api/UnityEngine.InputSystem.InputActionMap.html) or [`InputActionAsset`](../api/UnityEngine.InputSystem.InputActionAsset.html). - -Inputs that are used in combinations with other inputs may also lead to ambiguities. If, for example, the `b` key on the Keyboard is bound both on its own as well as in combination with the `shift` key, then if you first press `shift` and then `b`, the latter key press would be a valid input for either of the Actions. - -The way this is handled is that Bindings will be processed in the order of decreasing "complexity". This metric is derived automatically from the Binding: - -* A binding that is *not* part of a [composite](#composite-bindings) is assigned a complexity of 1. -* A binding that *is* part of a [composite](#composite-bindings) is assigned a complexity equal to the number of part bindings in the composite. - -In our example, this means that a [`OneModifier`](#one-modifier) composite Binding to `Shift+B` has a higher "complexity" than a Binding to `B` and thus is processed first. - -Additionally, the first Binding that results in the Action changing [phase](RespondingToActions.md#action-callbacks) will "consume" the input. This consuming will result in other Bindings to the same input not being processed. So in our example, when `Shift+B` "consumes" the `B` input, the Binding to `B` will be skipped. - -The following example illustrates how this works at the API level. - -```CSharp -// Create two actions in the same map. -var map = new InputActionMap(); -var bAction = map.AddAction("B"); -var shiftbAction = map.AddAction("ShiftB"); - -// Bind one of the actions to 'B' and the other to 'SHIFT+B'. -bAction.AddBinding("/b"); -shiftbAction.AddCompositeBinding("OneModifier") - .With("Modifier", "/shift") - .With("Binding", "/b"); - -// Print something to the console when the actions are triggered. -bAction.performed += _ => Debug.Log("B action performed"); -shiftbAction.performed += _ => Debug.Log("SHIFT+B action performed"); - -// Start listening to input. -map.Enable(); - -// Now, let's assume the left shift key on the keyboard is pressed (here, we manually -// press it with the InputTestFixture API). -Press(Keyboard.current.leftShiftKey); - -// And then the B is pressed. This is a valid input for both -// bAction as well as shiftbAction. -// -// What will happen now is that shiftbAction will do its processing first. In response, -// it will *perform* the action (i.e. we see the `performed` callback being invoked) and -// thus "consume" the input. bAction will stay silent as it will in turn be skipped over. -Press(keyboard.bKey); -``` - -### Initial state check - -After an Action is [enabled](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_enabled), it will start reacting to input as it comes in. However, at the time the Action is enabled, one or more of the Controls that are [bound](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_controls) to an action may already have a non-default state at that point. -x -Using what is referred to as an "initial state check", an Action can be made to respond to such a non-default state as if the state change happened *after* the Action was enabled. The way this works is that in the first input [update](../api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_Update_) after the Action was enabled, all its bound controls are checked in turn. If any of them has a non-default state, the Action responds right away. - -This check is implicitly enabled for [Value](RespondingToActions.md#value) actions. If, for example, you have a `Move` Action bound to the left stick on the gamepad and the stick is already pushed in a direction when `Move` is enabled, the character will immediately start walking. - -By default, [Button](RespondingToActions.md#button) and [Pass-Through](RespondingToActions.md#pass-through) type Actions, do not perform this check. A button that is pressed when its respective Action is enabled first needs to be released and then pressed again for it to trigger the Action. - -However, you can manually enable initial state checks on these types of Actions using the checkbox in the editor: - -![Initial State Check](./Images/InitialStateCheck.png) diff --git a/Packages/com.unity.inputsystem/Documentation~/Actions.md b/Packages/com.unity.inputsystem/Documentation~/Actions.md index 780d0e2ddc..e063b7459f 100644 --- a/Packages/com.unity.inputsystem/Documentation~/Actions.md +++ b/Packages/com.unity.inputsystem/Documentation~/Actions.md @@ -3,13 +3,13 @@ uid: input-system-actions --- # Actions -**Actions** are an important concept in the Input System. They allow you to separate the purpose of an input from the device controls which perform that input. Actions allow you to associate the purpose and device controls together in a flexible way. +**Actions** allow you to separate the purpose of an input from the device controls which perform that input. Actions allow you to associate the purpose and device controls together in a flexible way. -For example, the purpose of an input in a game might be to make the player's character move around. The device control associated with that action might be the motion of the left gamepad stick. +For example, the purpose of an input in a game might be to make the player's character move. The device control associated with that action might be the left gamepad stick. The association between an Action and the device controls which perform that input is a **binding**, and you can set up bindings in the [Input Actions editor](ActionsEditor.md). When you use Actions in your code, you do not need to refer to specific devices because the binding defines which device's controls are used to perform the action. -To use actions in your code, you must use the [Input Actions editor](ActionsEditor.md) to establish the mapping between the Action and one or more device controls. For example in this screenshot, the "Move" action is displayed, showing its bindings the left gamepad stick, and the keyboard's arrow keys. +To use actions in your code, you must use the [Input Actions editor](ActionsEditor.md) to configure the mapping between the Action and one or more device controls. For example in this screenshot, the "Move" action is displayed, showing its bindings the left gamepad stick, and the keyboard's arrow keys. ![Actions Bindings](Images/ActionsBinding.png)
*The Actions panel of the Input Actions Editor in Project Settings* @@ -23,136 +23,3 @@ Actions also make it simpler to create a system that lets your players [customiz > > - You can read input without using Actions and Bindings by directly reading specific device controls. This is less flexible, but can be quicker to implement for certain situations. Read more about [directly reading devices from script](Workflow-Direct.md). > -> - Although you can reorder actions in this window, the ordering is for visual convenience only, and does not affect the order in which the actions are triggered in your code. If multiple actions are performed in the same frame, the order in which they are reported by the input system is undefined. To avoid problems, you should not write code that assumes they will be reported in a particular order. ->
  - - -## Overview - -When scripting with Actions in the Input System, there are number of important API you can use, which are described here: - -|API name|Description| -|-----|-----------| -|[`InputSystem.actions`](../api/UnityEngine.InputSystem.InputSystem.html)|A reference to the set of actions assigned as the [project-wide Actions](./ProjectWideActions.md).| -|[`InputActionMap`](../api/UnityEngine.InputSystem.InputActionMap.html)|A named collection of Actions. The API equivalent to an entry in the "Action Maps" column of the [Input Actions editor](ActionsEditor.md).| -|[`InputAction`](../api/UnityEngine.InputSystem.InputAction.html)|A named Action that can return the current value of the controls that it is bound to, or can trigger callbacks in response to input. The API equivalent to an entry in the "Actions" column of the [Input Actions editor](ActionsEditor.md).| -|[`InputBinding`](../api/UnityEngine.InputSystem.InputBinding.html)|The relationship between an Action and the specific device controls for which it receives input. For more information about Bindings and how to use them, see [Action Bindings](ActionBindings.md).| - -Each Action has a name ([`InputAction.name`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_name)), which must be unique within the Action Map that the Action belongs to, if any (see [`InputAction.actionMap`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_actionMap)). Each Action also has a unique ID ([`InputAction.id`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_id)), which you can use to reference the Action. The ID remains the same even if you rename the Action. - -Each Action Map has a name ([`InputActionMap.name`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_name)), which must also be unique with respect to the other Action Maps present, if any. Each Action Map also has a unique ID ([`InputActionMap.id`](../api/UnityEngine.InputSystem.InputActionMap.html#UnityEngine_InputSystem_InputActionMap_id)), which you can use to reference the Action Map. The ID remains the same even if you rename the Action Map. - -## Creating Actions - -The simplest way to create actions is to use the [Input Actions editor](ActionsEditor.md) in the Project Settings window. This is the primary recommended workflow and suitable for most scenarios. - -However, because the input system API is very open, there are many other ways to create actions which may suit less common scenarios. For example, by loading actions from JSON data, or creating actions entirely in code. - -### Creating Actions using the Action editor - -For information on how to create and edit Input Actions in the editor, see the [Input Actions editor](ActionsEditor.md). This is the recommended workflow if you want to organise all your input actions and bindings in one place, which applies across the whole of your project. This often the case for most types of game or app. - -![Action Editor Window](Images/ProjectSettingsInputActionsSimpleShot.png) -*The Input Actions Editor in the Project Settings window* - - -# Other ways to create Actions - -The simplest way to create actions is to use the [Input Actions editor](ActionsEditor.md) to configure a set of actions in an asset, as described above. However, because the Input System package API is open and flexible, you can create actions using alternative techniques. These alternatives might be more suitable if you want to customize your project beyond the standard workflow. - -### Creating Actions by declaring them in MonoBehaviours - -As an alternative workflow, you can declare individual [Input Action](../api/UnityEngine.InputSystem.InputAction.html) and [Input Action Maps](../api/UnityEngine.InputSystem.InputActionMap.html) as fields directly inside `MonoBehaviour` components. - -```CSharp -using UnityEngine; -using UnityEngine.InputSystem; - -public class ExampleScript : MonoBehaviour -{ - public InputAction move; - public InputAction jump; -} -``` - -The result is similar to using an Actions defined in the Input Actions editor, except the Actions are defined in the GameObject's properties and saved as Scene or Prefab data, instead of in a dedicated Asset. - -When you embed actions like this, by defining serialized InputAction fields in a MonoBehaviour, the GameObject's Inspector window displays an interface similar to the Actions column of the [Actions Editor](./ActionsEditor.md), which allows you to set up the bindings for those actions. For example: - -![MyBehavior Inspector](Images/Workflow-EmbeddedActionsInspector.png) - -* To add or remove Actions or Bindings, click the Add (+) or Remove (-) icon in the header. -* To edit Bindings, double-click them.
-* To edit Actions, double-click them in an Action Map, or click the gear icon on individual Action properties.
-* You can also right-click entries to bring up a context menu, and you can drag them. Hold the Alt key and drag an entry to duplicate it. - -Unlike the project-wide actions in the Project Settings window, you must manually enable and disable Actions and Action Maps that are embedded in MonoBehaviour components. - -When you use this workflow, the serialised action configurations are stored with the parent GameObject as part of the scene, opposite to being serialised with an Action Asset. This can be useful if you want to bundle the control bindings and behaviour together in a single monobehaviour or prefab, so it can be distributed together. However, this can also make it harder to organize your full set of control bindings if they are distributed across multiple prefabs or scenes. - -### Loading Actions from JSON - -You can load Actions as JSON in the form of a set of Action Maps or as a full [`InputActionAsset`](../api/UnityEngine.InputSystem.InputActionAsset.html). This also works at runtime in the Player. - -```CSharp -// Load a set of action maps from JSON. -var maps = InputActionMap.FromJson(json); - -// Load an entire InputActionAsset from JSON. -var asset = InputActionAsset.FromJson(json); -``` - -### Creating Actions in code - -You can manually create and configure Actions entirely in code, including assigning the bindings. This also works at runtime in the Player. For example: - -```CSharp -// Create free-standing Actions. -var lookAction = new InputAction("look", binding: "/leftStick"); -var moveAction = new InputAction("move", binding: "/rightStick"); - -lookAction.AddBinding("/delta"); -moveAction.AddCompositeBinding("Dpad") - .With("Up", "/w") - .With("Down", "/s") - .With("Left", "/a") - .With("Right", "/d"); - -// Create an Action Map with Actions. -var map = new InputActionMap("Gameplay"); -var lookAction = map.AddAction("look"); -lookAction.AddBinding("/leftStick"); - -// Create an Action Asset. -var asset = ScriptableObject.CreateInstance(); -var gameplayMap = new InputActionMap("gameplay"); -asset.AddActionMap(gameplayMap); -var lookAction = gameplayMap.AddAction("look", "/leftStick"); -``` - -Any action that you create in this way during Play mode do not persist in the Input Action Asset after you exit Play mode. This means you can test your application in a realistic manner in the Editor without having to worry about inadvertently modifying the asset. - - -## Enabling actions - -Actions have an **enabled** state, meaning you can enable or disable them to suit different situations. - -If you have an Action Asset assigned as [project-wide](./ProjectWideActions.md), the actions it contains are enabled by default and ready to use. - -For actions defined elsewhere, such as in an Action Asset not assigned as project-wide, or defined your own code, they begin in a disabled state, and you must enable them before they will respond to input. - -You can enable actions individually, or as a group by enabling the Action Map which contains them. - -```CSharp -// Enable a single action. -lookAction.Enable(); - -// Enable an en entire action map. -gameplayActions.Enable(); -``` - -When you enable an Action, the Input System resolves its bindings, unless it has done so already, or if the set of devices that the Action can use has not changed. For more details about this process, see the documentation on [binding resolution](ActionBindings.md#binding-resolution). - -You can't change certain aspects of the configuration, such Action Bindings, while an Action is enabled. To stop Actions or Action Maps from responding to input, call [`Disable`](../api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_Disable). - -While enabled, an Action actively monitors the [Control(s)](Controls.md) it's bound to. If a bound Control changes state, the Action processes the change. If the Control's change represents an [Interaction](Interactions.md) change, the Action creates a response. All of this happens during the Input System update logic. Depending on the [update mode](Settings.md#update-mode) selected in the input settings, this happens once every frame, once every fixed update, or manually if updates are set to manual. diff --git a/Packages/com.unity.inputsystem/Documentation~/Controls.md b/Packages/com.unity.inputsystem/Documentation~/Controls.md index 19292386ea..db21787921 100644 --- a/Packages/com.unity.inputsystem/Documentation~/Controls.md +++ b/Packages/com.unity.inputsystem/Documentation~/Controls.md @@ -3,15 +3,15 @@ uid: input-system-controls --- # Controls -* [Hierarchies](#control-hierarchies) -* [Types](#control-types) -* [Usages](#control-usages) -* [Paths](#control-paths) -* [State](#control-state) -* [Actuation](#control-actuation) -* [Noisy Controls](#noisy-controls) -* [Synthetic Controls](#synthetic-controls) -* [Performance Optimization](#performance-optimization) +- [Control paths](#control-paths) +- [Control state](#control-state) +- [Control actuation](#control-actuation) +- [Noisy Controls](#noisy-controls) +- [Synthetic Controls](#synthetic-controls) +- [Performance Optimization](#performance-optimization) + - [Avoiding defensive copies](#avoiding-defensive-copies) + - [Control Value Caching](#control-value-caching) + - [Optimized control read value](#optimized-control-read-value) An Input Control represents a source of values. These values can be of any structured or primitive type. The only requirement is that the type is [blittable](https://docs.microsoft.com/en-us/dotnet/framework/interop/blittable-and-non-blittable-types). @@ -23,263 +23,6 @@ Additionally, a Control might have one or more aliases which provide alternative Finally, a Control might also have a short display name which can be accessed through the [`InputControl.shortDisplayName`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_shortDisplayName) property. For example, the short display name for the left mouse button is "LMB". -## Control hierarchies -Controls can form hierarchies. The root of a Control hierarchy is always a [Device](Devices.md). -The setup of hierarchies is exclusively controlled through [layouts](Layouts.md). -You can access the parent of a Control using [`InputControl.parent`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_parent), and its children using [`InputControl.children`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_children). To access the flattened hierarchy of all Controls on a Device, use [`InputDevice.allControls`](../api/UnityEngine.InputSystem.InputDevice.html#UnityEngine_InputSystem_InputDevice_allControls). - -## Control types - -All controls are based on the [`InputControl`](../api/UnityEngine.InputSystem.InputControl.html) base class. Most concrete implementations are based on [`InputControl`](../api/UnityEngine.InputSystem.InputControl-1.html). - -The Input System provides the following types of controls out of the box: - -|Control Type|Description|Example| -|------------|-----------|-------| -|[`AxisControl`](../api/UnityEngine.InputSystem.Controls.AxisControl.html)|A 1D floating-point axis.|[`Gamepad.leftStick.x`](../api/UnityEngine.InputSystem.Controls.Vector2Control.html#UnityEngine_InputSystem_Controls_Vector2Control_x)| -|[`ButtonControl`](../api/UnityEngine.InputSystem.Controls.ButtonControl.html)|A button expressed as a floating-point value. Whether the button can have a value other than 0 or 1 depends on the underlying representation. For example, gamepad trigger buttons can have values other than 0 and 1, but gamepad face buttons generally can't.|[`Mouse.leftButton`](../api/UnityEngine.InputSystem.Mouse.html#UnityEngine_InputSystem_Mouse_leftButton)| -|[`KeyControl`](../api/UnityEngine.InputSystem.Controls.KeyControl.html)|A specialized button that represents a key on a [`Keyboard`](../api/UnityEngine.InputSystem.Keyboard.html). Keys have an associated [`keyCode`](../api/UnityEngine.InputSystem.Controls.KeyControl.html#UnityEngine_InputSystem_Controls_KeyControl_keyCode) and, unlike other types of Controls, change their display name in accordance to the currently active system-wide keyboard layout. See the [Keyboard](Keyboard.md) documentation for details.|[`Keyboard.aKey`](../api/UnityEngine.InputSystem.Keyboard.html#UnityEngine_InputSystem_Keyboard_aKey)| -|[`Vector2Control`](../api/UnityEngine.InputSystem.Controls.Vector2Control.html)|A 2D floating-point vector.|[`Pointer.position`](../api/UnityEngine.InputSystem.Pointer.html#UnityEngine_InputSystem_Pointer_position)| -|[`Vector3Control`](../api/UnityEngine.InputSystem.Controls.Vector3Control.html)|A 3D floating-point vector.|[`Accelerometer.acceleration`](../api/UnityEngine.InputSystem.Accelerometer.html#UnityEngine_InputSystem_Accelerometer_acceleration)| -|[`QuaternionControl`](../api/UnityEngine.InputSystem.Controls.QuaternionControl.html)|A 3D rotation.|[`AttitudeSensor.attitude`](../api/UnityEngine.InputSystem.AttitudeSensor.html#UnityEngine_InputSystem_AttitudeSensor_attitude)| -|[`IntegerControl`](../api/UnityEngine.InputSystem.Controls.IntegerControl.html)|An integer value.|[`Touchscreen.primaryTouch.touchId`](../api/UnityEngine.InputSystem.Controls.TouchControl.html#UnityEngine_InputSystem_Controls_TouchControl_touchId)| -|[`StickControl`](../api/UnityEngine.InputSystem.Controls.StickControl.html)|A 2D stick control like the thumbsticks on gamepads or the stick control of a joystick.|[`Gamepad.rightStick`](../api/UnityEngine.InputSystem.Gamepad.html#UnityEngine_InputSystem_Gamepad_rightStick)| -|[`DpadControl`](../api/UnityEngine.InputSystem.Controls.DpadControl.html)|A 4-way button control like the D-pad on gamepads or hatswitches on joysticks.|[`Gamepad.dpad`](../api/UnityEngine.InputSystem.Gamepad.html#UnityEngine_InputSystem_Gamepad_dpad)| -|[`TouchControl`](../api/UnityEngine.InputSystem.Controls.TouchControl.html)|A control that represents all the properties of a touch on a [touch screen](Touch.md).|[`Touchscreen.primaryTouch`](../api/UnityEngine.InputSystem.Touchscreen.html#UnityEngine_InputSystem_Touchscreen_primaryTouch)| - -You can browse the set of all registered control layouts in the [input debugger](Debugging.md#debugging-layouts). - -## Control usages - -A Control can have one or more associated usages. A usage is a string that denotes the Control's intended use. An example of a Control usage is `Submit`, which labels a Control that is commonly used to confirm a selection in the UI. On a gamepad, this usage is commonly found on the `buttonSouth` Control. - -You can access a Control's usages using the [`InputControl.usages`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_usages) property. - -Usages can be arbitrary strings. However, a certain set of usages is very commonly used and comes predefined in the API in the form of the [`CommonUsages`](../api/UnityEngine.InputSystem.CommonUsages.html) static class. Check out the [`CommonUsages` scripting API page](../api/UnityEngine.InputSystem.CommonUsages.html) for an overview. - -## Control paths - ->Example: `/leftStick/x` means "X Control on left stick of gamepad". - -The Input System can look up Controls using textual paths. [Bindings](ActionBindings.md) on Input Actions rely on this feature to identify the Control(s) they read input from. However, you can also use them for lookup directly on Controls and Devices, or to let the Input System search for Controls among all devices using [`InputSystem.FindControls`](../api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_FindControls_System_String_). - -```CSharp -var gamepad = Gamepad.all[0]; -var leftStickX = gamepad["leftStick/x"]; -var submitButton = gamepad["{Submit}"]; -var allSubmitButtons = InputSystem.FindControls("*/{Submit}"); -``` - -Control paths resemble file system paths. Each path consists of one or more components separated by a forward slash: - - component/component... - -Each component uses a similar syntax made up of multiple fields. Each field is optional, but at least one field must be present. All fields are case-insensitive. - - {usageName}controlName#(displayName) - -The following table explains the use of each field: - -|Field|Description|Example| -|-----|-----------|-------| -|``|Requires the Control at the current level to be based on the given layout. The actual layout of the Control may be the same or a layout *based* on the given layout.|`/buttonSouth`| -|`{usageName}`|Works differently for Controls and Devices.

When used on a Device (the first component of a path), it requires the device to have the given usage. See [Device usages](Devices.md#device-usages) for more details.

For looking up a Control, the usage field is currently restricted to the path component immediately following the Device (the second component in the path). It finds the Control on the Device that has the given usage. The Control can be anywhere in the Control hierarchy of the Device.|Device:

`{LeftHand}/trigger`

Control:

`/{Submit}`| -|`controlName`|Requires the Control at the current level to have the given name. Takes both "proper" names ([`InputControl.name`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_name)) and aliases ([`InputControl.aliases`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_aliases)) into account.

This field can also be a wildcard (`*`) to match any name.|`MyGamepad/buttonSouth`

`*/{PrimaryAction}` (match `PrimaryAction` usage on Devices with any name)| -|`#(displayName)`|Requires the Control at the current level to have the given display name (i.e. [`InputControl.displayName`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_displayName)). The display name may contain whitespace and symbols.|`/#(a)` (matches the key that generates the "a" character, if any, according to the current keyboard layout).

`/#(Cross)`| - -You can access the literal path of a given control via its [`InputControl.path`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_path) property. - -If needed, you can manually parse a control path into its components using the [`InputControlPath.Parse(path)`](../api/UnityEngine.InputSystem.InputControlPath.html#UnityEngine_InputSystem_InputControlPath_Parse_System_String_) API. - -```CSharp -var parsed = InputControlPath.Parse("{LeftHand}/trigger").ToArray(); - -Debug.Log(parsed.Length); // Prints 2. -Debug.Log(parsed[0].layout); // Prints "XRController". -Debug.Log(parsed[0].name); // Prints an empty string. -Debug.Log(parsed[0].usages.First()); // Prints "LeftHand". -Debug.Log(parsed[1].layout); // Prints null. -Debug.Log(parsed[1].name); // Prints "trigger". -``` - -## Control state - -Each Control is connected to a block of memory that is considered the Control's "state". You can query the size, format, and location of this block of memory from a Control through the [`InputControl.stateBlock`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_stateBlock) property. - -The state of Controls is stored in unmanaged memory that the Input System handles internally. All Devices added to the system share one block of unmanaged memory that contains the state of all the Controls on the Devices. - -A Control's state might not be stored in the natural format for that Control. For example, the system often represents buttons as bitfields, and axis controls as 8-bit or 16-bit integer values. This format is determined by the combination of platform, hardware, and drivers. Each Control knows the format of its storage and how to translate the values as needed. The Input System uses [layouts](Layouts.md) to understand this representation. - -You can access the current state of a Control through its [`ReadValue`](../api/UnityEngine.InputSystem.InputControl-1.html#UnityEngine_InputSystem_InputControl_1_ReadValue) method. - -```CSharp -Gamepad.current.leftStick.x.ReadValue(); -``` - -Each type of Control has a specific type of values that it returns, regardless of how many different types of formats it supports for its state. You can access this value type through the [`InputControl.valueType`](../api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_valueType) property. - -Reading a value from a Control might apply one or more value Processors. See documentation on [Processors](Processors.md) for more information. - -[//]: # (#### Default State - TODO) - -[//]: # (#### Reading State vs Reading Values - TODO) - -#### Recording state history - -You might want to access the history of value changes on a Control (for example, in order to compute exit velocity on a touch release). - -To record state changes over time, you can use [`InputStateHistory`](../api/UnityEngine.InputSystem.LowLevel.InputStateHistory.html) or [`InputStateHistory`](../api/UnityEngine.InputSystem.LowLevel.InputStateHistory-1.html). The latter restricts Controls to those of a specific value type, which in turn simplifies some of the API. - -```CSharp -// Create history that records Vector2 control value changes. -// NOTE: You can also pass controls directly or use paths that match multiple -// controls (e.g. "/