### Finding InputAction References Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Workflow-Actions.md In the Start() method, use InputSystem.actions.FindAction() to get references to your Input Actions and store them in their respective variables. Avoid using FindAction in Update() for performance reasons. ```csharp moveAction = InputSystem.actions.FindAction("Move"); jumpAction = InputSystem.actions.FindAction("Jump"); ``` -------------------------------- ### Complete Example Script Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Workflow-Actions.md This script demonstrates how to declare, find, and read values from Input Actions for movement and jumping. ```csharp using UnityEngine; using UnityEngine.InputSystem; public class Example : MonoBehaviour { // These variables are to hold the Action references InputAction moveAction; InputAction jumpAction; private void Start() { // Find the references to the "Move" and "Jump" actions moveAction = InputSystem.actions.FindAction("Move"); jumpAction = InputSystem.actions.FindAction("Jump"); } void Update() { // Read the "Move" action value, which is a 2D vector // and the "Jump" action state, which is a boolean value Vector2 moveValue = moveAction.ReadValue(); // your movement code here if (jumpAction.IsPressed()) { // your jump code here } } } ``` -------------------------------- ### Start Interactive Rebinding with Default Configuration Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/CHANGELOG.md Initiates an interactive rebind operation for an action using the default configuration. This reduces the need for manual setup of the rebind. ```CSharp // Start a rebind with the default configuration. myAction.PerformInteractiveRebinding().Start(); ``` -------------------------------- ### Implement a custom IInputInteraction Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Interactions.md Create a custom interaction by implementing the IInputInteraction interface. This example demonstrates a wiggle interaction that tracks state and uses timers. ```CSharp // Interaction which performs when you quickly move an // axis all the way from extreme to the other. public class MyWiggleInteraction : IInputInteraction { public float duration = 0.2; void Process(ref InputInteractionContext context) { if (context.timerHasExpired) { context.Canceled(); return; } switch (context.phase) { case InputActionPhase.Waiting: if (context.Control.ReadValue() == 1) { context.Started(); context.SetTimeout(duration); } break; case InputActionPhase.Started: if (context.Control.ReadValue() == -1) context.Performed(); break; } } // Unlike processors, Interactions can be stateful, meaning that you can keep a // local state that mutates over time as input is received. The system might // invoke the Reset() method to ask Interactions to reset to the local state // at certain points. void Reset() { } } ``` -------------------------------- ### Control Path Example Source: https://github.com/unity-technologies/inputsystem/blob/develop/Docs/Presentation/InputSystem-TheGrandTour.html Demonstrates the path language used to address controls within the Input System. This format is used for defining bindings. ```plaintext {LeftHand}/trigger ``` -------------------------------- ### Add InputSystemUIInputModule and Install Default Actions Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/CHANGELOG.md When adding InputSystemUIInputModule from code, DefaultInputActions are now automatically installed. This ensures the UI module is set up with default actions, similar to adding the component in the editor. ```CSharp var go = new GameObject(); go.AddComponent(); var uiModule = go.AddComponent(); // uiModule.actionsAsset now has a DefaultInputActions() asset assigned to it and the various // action references point to its actions. ``` -------------------------------- ### Setup On-Screen Controls via Code Source: https://context7.com/unity-technologies/inputsystem/llms.txt This script demonstrates how to programmatically add and configure OnScreenButton and OnScreenStick components for mobile virtual controls. Ensure the RectTransform objects are assigned in the inspector. ```csharp using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.OnScreen; // Setting up on-screen controls via code public class OnScreenControlsSetup : MonoBehaviour { public RectTransform buttonTransform; public RectTransform stickTransform; void Start() { // Add OnScreenButton component var button = buttonTransform.gameObject.AddComponent(); button.controlPath = "/buttonSouth"; // Maps to A button // Add OnScreenStick component var stick = stickTransform.gameObject.AddComponent(); stick.controlPath = "/leftStick"; stick.movementRange = 50f; // Pixels the stick can move } } ``` -------------------------------- ### Instantiate and enable DefaultInputActions in C# Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/ActionAssets.md Create an instance of the default actions class and subscribe to input events. Ensure the actions are enabled to start receiving input. ```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(); } ``` -------------------------------- ### Handling Multiple Input Sequences with Composites Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md Demonstrates how to create and bind multiple actions, including a composite action with a modifier, to handle input sequences. This example shows how the Input System prioritizes and consumes input based on binding complexity, preventing simpler bindings from triggering when a more complex one is matched. ```CSharp var map = new InputActionMap(); var bAction = map.AddAction("B"); var shiftbAction = map.AddAction("ShiftB"); bAction.AddBinding("/b"); shiftbAction.AddCompositeBinding("OneModifier") .With("Modifier", "/shift") .With("Binding", "/b"); bAction.performed += _ => Debug.Log("B action performed"); shiftbAction.performed += _ => Debug.Log("SHIFT+B action performed"); map.Enable(); Press(Keyboard.current.leftShiftKey); Press(keyboard.bKey); ``` -------------------------------- ### Processor Stack Example Source: https://github.com/unity-technologies/inputsystem/blob/develop/Docs/Presentation/InputSystem-TheGrandTour.html Shows how to apply a stack of processors to incoming control values. Processors modify the raw input data before it's used by actions. ```plaintext invert,scale(factor=2) ``` -------------------------------- ### Register Action Callbacks Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/RespondingToActions.md Shows how to register callbacks for the started, performed, and canceled phases of an InputAction. Use this for event-driven input handling. ```CSharp var action = new InputAction(); action.started += context => /* Action was started */; action.performed += context => /* Action was performed */; action.canceled += context => /* Action was canceled */; ``` -------------------------------- ### Listen for Event and Button Changes Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/CHANGELOG.md Provides examples for using the new event listening API to monitor device events and button presses. ```CSharp InputSystem.onEvent .ForDevice() .Where(e => e.HasButtonPress()) .CallOnce(e => Debug.Log("Button pressed!)); ``` ```CSharp InputSystem.onAnyButtonPress .CallOnce(ctrl => Debug.Log($"Button '{ctrl}' pressed")); ``` -------------------------------- ### Query Input Devices Source: https://github.com/unity-technologies/inputsystem/wiki/How-Do-I... Examples of querying input devices using the InputSystem. This includes selecting devices based on type, querying controls using templates, and searching by name. ```C# // Go through all devices and select gamepads. InputSystem.devices.Select(x => x is Gamepad); ``` ```C# // Query everything that is using the gamepad template or based on that template. InputSystem.GetControls("/"); ``` ```C# // Fetch all devices with "gamepad" in their names (not a good idea; no guarantee // a gamepad is actually named that way). InputSystem.GetControls("/gamepad*"); ``` -------------------------------- ### Demonstrate Parameter Override Specificity Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md Illustrates how multiple parameter overrides at different scopes (action, action map, asset) are resolved, with more specific overrides taking precedence. This example shows overrides for 'tap:duration' at action, action with group, and asset levels. ```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); ``` -------------------------------- ### Implement Charged Shooting with Input Actions Source: https://github.com/unity-technologies/inputsystem/blob/develop/Assets/Samples/SimpleDemo/README.md Shows how to use Tap and SlowTap interactions on a fire action for a charged shooting mechanism. Firing logic is handled via action callbacks (started, performed, canceled). ```CSharp fireAction.performed += ctx => { if (ctx.interaction is SlowTapInteraction) { StartCoroutine(BurstFire((int)(ctx.duration * burstSpeed))); } else { Fire(); } m_Charging = false; }; fireAction.started += ctx => { if (ctx.interaction is SlowTapInteraction) m_Charging = true; }; fireAction.canceled += ctx => { m_Charging = false; }; ``` -------------------------------- ### Instantiate PlayerInput with Specific Control Scheme Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Testing.md Use `InputSystem.AddDevice()` to add devices and `PlayerInput.Instantiate` to create a player with a specific control scheme. Asserts verify the assigned devices and control scheme. ```CSharp [Test] public void PlayerInput_CanInstantiatePlayer_WithSpecificControlScheme() { InputSystem.AddDevice(); var keyboard = InputSystem.AddDevice(); var mouse = InputSystem.AddDevice(); var prefab = new GameObject(); prefab.SetActive(false); var prefabPlayerInput = prefab.AddComponent(); prefabPlayerInput.actions = InputActionAsset.FromJson(kActions); var player = PlayerInput.Instantiate(prefab, controlScheme: "Keyboard&Mouse"); Assert.That(player.devices, Is.EquivalentTo(new InputDevice[] { keyboard, mouse })); Assert.That(player.controlScheme, Is.EqualTo("Keyboard&Mouse")); } ``` -------------------------------- ### Interaction Example Source: https://github.com/unity-technologies/inputsystem/blob/develop/Docs/Presentation/InputSystem-TheGrandTour.html Illustrates the use of interactions to define how input events are interpreted. This example specifies a multitap interaction. ```plaintext multitap(tapCount=3) ``` -------------------------------- ### Responding to Actions using Callbacks Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/RespondingToActions.md Explains different methods for setting up callbacks to respond to input actions, including the PlayerInput component and direct action callbacks. ```APIDOC ## API: Responding to Actions via Callbacks ### Description This API documentation outlines various strategies for responding to input actions through callbacks. It covers using the `PlayerInput` component for inspector-based setup, direct action callbacks (`started`, `performed`, `canceled`), Action Map callbacks (`actionTriggered`), global Input System callbacks (`InputSystem.onActionChange`), and `InputActionTrace` for recording changes. ### Method None (Conceptual API) ### Endpoint None ### Parameters None ### Request Example None ### Response None ### Callbacks Overview 1. **PlayerInput Component**: Simplest method, allows setting up callbacks directly in the inspector. [Read more](xref:input-system-workflow-player-input). 2. **Action Callbacks**: Each `InputAction` has `started`, `performed`, and `canceled` callbacks. 3. **Action Map Callback**: Each `InputActionMap` has an `actionTriggered` callback. 4. **Global Callback**: The Input System has a global `InputSystem.onActionChange` callback. 5. **InputActionTrace**: Can record changes happening on Actions. ### Action Callbacks Example Every `InputAction` can go through distinct phases. You can register callbacks for `started`, `performed`, and `canceled` phases. ```CSharp var action = new InputAction(); action.started += context => /* Action was started */; action.performed += context => /* Action was performed */; action.canceled += context => /* Action was canceled */; ``` Each callback receives an `InputAction.CallbackContext` which provides context information and allows reading values from triggering controls using `InputAction.CallbackContext.ReadValue`. ``` -------------------------------- ### Button InputAction Behavior Change Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/CHANGELOG.md Illustrates how Button type InputActions now handle the 'started' phase when a button press is released but not fully deactuated. This change ensures buttons remain in 'started' or 'performed' as long as their value is not 0. ```CSharp // Before: Set(Gamepad.current.rightTrigger, 0.7f); // Performed (pressed) Set(Gamepad.current.rightTrigger, 0.2f); // Canceled (released) Set(Gamepad.current.rightTrigger, 0.1f); // Started!! Set(Gamepad.current.rightTrigger, 0f); // Canceled // Now: Set(Gamepad.current.rightTrigger, 0.7f); // Performed (pressed) Set(Gamepad.current.rightTrigger, 0.2f); // Started (released but not fully) Set(Gamepad.current.rightTrigger, 0.1f); // Set(Gamepad.current.rightTrigger, 0f); // Canceled ``` -------------------------------- ### Create and Simulate Virtual Devices Source: https://context7.com/unity-technologies/inputsystem/llms.txt Create virtual input devices like keyboards and gamepads for testing purposes. You can simulate input events on these virtual devices. ```csharp // Creating virtual/simulated devices for testing public class VirtualDeviceExample : MonoBehaviour { private Keyboard virtualKeyboard; private Gamepad virtualGamepad; void CreateVirtualDevices() { // Add virtual keyboard virtualKeyboard = InputSystem.AddDevice(); // Add virtual gamepad virtualGamepad = InputSystem.AddDevice(); // Simulate input on virtual devices using (StateEvent.From(virtualKeyboard, out var eventPtr)) { virtualKeyboard.spaceKey.WriteValueIntoEvent(1f, eventPtr); InputSystem.QueueEvent(eventPtr); } } void SimulateGamepadInput() { // Queue gamepad state InputSystem.QueueStateEvent(virtualGamepad, new GamepadState { leftStick = new Vector2(0.5f, 0.8f), buttons = (uint)(1 << (int)GamepadButton.South) }); } void OnDestroy() { if (virtualKeyboard != null) InputSystem.RemoveDevice(virtualKeyboard); if (virtualGamepad != null) InputSystem.RemoveDevice(virtualGamepad); } } ``` -------------------------------- ### InputAction.WasReleasedThisFrame() Example Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/RespondingToActions.md Demonstrates how to check if an action was released this frame using InputAction.WasReleasedThisFrame(). ```APIDOC ## GET /unity-technologies/inputsystem/InputAction.WasReleasedThisFrame ### Description Checks if the actuation level of an action has gone from at or above the press point to at or below the release threshold within the current frame. ### Method GET ### Endpoint /unity-technologies/inputsystem/InputAction.WasReleasedThisFrame ### Parameters None ### Request Example None ### Response #### Success Response (200) - **bool** (boolean) - True if the action was released this frame, false otherwise. #### Response Example { "example": "true" } ``` -------------------------------- ### Get All Connected Gamepads Source: https://github.com/unity-technologies/inputsystem/wiki/How-Do-I... Retrieve a list of all currently connected gamepad devices. ```C# var allGamepads = Gamepad.all; ``` -------------------------------- ### Manage Gyroscope State Source: https://github.com/unity-technologies/inputsystem/wiki/OldVsNewInputSystem Get the enabled state of the gyroscope or toggle it using the InputSystem. ```csharp // Get. Gyro.current.enabled // Set. InputSystem.EnableDevice(Gyro.current); InputSystem.DisableDevice(Gyro.current); ``` -------------------------------- ### Manage Compass State Source: https://github.com/unity-technologies/inputsystem/wiki/OldVsNewInputSystem Get the enabled state of the compass or toggle it using the InputSystem. ```csharp // Get. Compass.current.enabled // Set. InputSystem.EnableDevice(Compass.current); InputSystem.DisableDevice(Compass.current); ``` -------------------------------- ### Initialize InputAction with Binding Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/CHANGELOG.md Demonstrates how to initialize an InputAction with a binding directly. Previously, this could lead to the binding not showing in the inspector. ```CSharp public class MyMB : MonoBehaviour { // This would end up not showing the binding in the inspector. public InputAction action = new InputAction(binding: "/leftStick"); } ``` -------------------------------- ### Create and Enable Input Action Programmatically Source: https://github.com/unity-technologies/inputsystem/wiki/How-Do-I... Demonstrates creating an InputAction directly in code, binding it to a control path, and enabling it to listen for input. ```C# // Create action that binds to the primary action control on all devices. var action = new InputAction(binding: "*/{primaryAction}"); // Have it run your code when action is triggered. action.performed += _ => Fire(); // Start listening for control changes. action.Enable(); ``` -------------------------------- ### HingeAngle Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Sensors.md Represents hinge angle for foldable devices. Includes C# code examples for usage. ```APIDOC ## HingeAngle ### Description This Input Device represents hinge angle for foldable devices. For ex., Google Fold Android phone. ### Method GET ### Endpoint /unity-technologies/inputsystem/hingeangle ### Request Example ```CSharp [Serializable] class SensorCapabilities { public int sensorType; public float resolution; public int minDelay; } void Start() { if (HingeAngle.current != null) { InputSystem.EnableDevice(HingeAngle.current); var caps = JsonUtility.FromJson(HingeAngle.current.description.capabilities); Debug.Log($"HingeAngle Capabilities: resolution = {caps.resolution}, minDelay = {caps.minDelay}"); } } void Update() { if (HingeAngle.current != null) Debug.Log($"HingeAngle={HingeAngle.current.angle.ReadValue()}"); } ``` ### Response Example ```json { "angle": "float" } ``` ``` -------------------------------- ### Mock Third-Party API Callbacks Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Devices.md Example structure for an external API that provides device connection and disconnection events. ```CSharp public static ThirdPartyAPI { // This example assumes that the argument is a string that // contains the name of the Device, and that no two Devices // have the same name in the external API. public static Action deviceAdded; public static Action deviceRemoved; } ``` -------------------------------- ### Basic Action Handling in C# Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/RespondingToActions.md Illustrates how to find actions and check their states (IsPressed, WasPressedThisFrame, WasReleasedThisFrame) within the Update loop. ```APIDOC ## C# Example: Basic Action Handling ### Description This C# script demonstrates how to initialize and use `InputAction` objects in Unity. It shows how to find actions by name and check their states within the `Update` method for common input scenarios like checking if an action is currently pressed, was pressed this frame, or was released this frame. ### Method None (Illustrative C# code) ### Endpoint None ### Parameters None ### Request Example None ### Response None ### Code Example ```CSharp using UnityEngine; using UnityEngine.InputSystem; public class Example : MonoBehaviour { InputAction shieldAction; InputAction teleportAction; InputAction submitAction; private void Start() { shieldAction = InputSystem.actions.FindAction("Shield"); teleportAction = InputSystem.actions.FindAction("Teleport"); submitAction = InputSystem.actions.FindAction("Submit"); } void Update() { if (shieldAction.IsPressed()) { // shield is active for every frame that the shield action is pressed } if (teleportAction.WasPressedThisFrame()) { // teleport occurs on the first frame that the action is pressed, and not again until the button is released } if (submitAction.WasReleasedThisFrame()) { // submit occurs on the frame that the action is released, a common technique for buttons relating to UI controls. } } } ``` ``` -------------------------------- ### Configure Input Interactions in C# Source: https://context7.com/unity-technologies/inputsystem/llms.txt Demonstrates how to attach various interaction types like tap, hold, multi-tap, and press behaviors to InputActions. ```csharp using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Interactions; public class InteractionsExample : MonoBehaviour { private InputAction fireAction; private InputAction chargeAction; private InputAction doubleTapAction; void Awake() { // Tap interaction (quick press and release) fireAction = new InputAction("fire"); fireAction.AddBinding("/buttonSouth") .WithInteraction("tap"); // Hold interaction (press and hold for duration) chargeAction = new InputAction("charge"); chargeAction.AddBinding("/buttonSouth") .WithInteraction("hold(duration=0.5)"); // Combined tap and slow tap var combinedAction = new InputAction("combined"); combinedAction.AddBinding("/buttonSouth") .WithInteractions("tap;slowTap(duration=0.8)"); combinedAction.started += ctx => { if (ctx.interaction is SlowTapInteraction) ShowChargingUI(); }; combinedAction.performed += ctx => { if (ctx.interaction is SlowTapInteraction) ChargedFire(); else if (ctx.interaction is TapInteraction) QuickFire(); }; combinedAction.canceled += ctx => HideChargingUI(); // Multi-tap interaction (double tap, triple tap) doubleTapAction = new InputAction("doubleTap"); doubleTapAction.AddBinding("/space") .WithInteraction("multiTap(tapCount=2,tapTime=0.3,tapDelay=0.3)"); // Press interaction with behavior options var pressAction = new InputAction("press"); // PressOnly - trigger on press pressAction.AddBinding("/f") .WithInteraction("press(behavior=0)"); // ReleaseOnly - trigger on release pressAction.AddBinding("/g") .WithInteraction("press(behavior=1)"); // PressAndRelease - trigger on both pressAction.AddBinding("/h") .WithInteraction("press(behavior=2)"); fireAction.performed += ctx => Debug.Log("Tap fire!"); chargeAction.performed += ctx => Debug.Log("Charge complete!"); doubleTapAction.performed += ctx => Debug.Log("Double tap!"); } void OnEnable() { fireAction.Enable(); chargeAction.Enable(); doubleTapAction.Enable(); } void ShowChargingUI() => Debug.Log("Charging..."); void HideChargingUI() => Debug.Log("Charge cancelled"); void ChargedFire() => Debug.Log("Charged shot!"); void QuickFire() => Debug.Log("Quick shot!"); } ``` -------------------------------- ### 1D Axis Composite Binding Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md Example of how to add a 1D Axis Composite binding to an action, mapping positive and negative controls. ```APIDOC ## Add 1D Axis Composite Binding ### Description This example demonstrates how to add a 1D Axis Composite binding to an action. The composite uses two button inputs to control the positive and negative directions of a 1D axis. ### Method ```CSharp myAction.AddCompositeBinding("1DAxis") // Or just "Axis" .With("Positive", "/rightTrigger") .With("Negative", "/leftTrigger"); ``` ### Parameters #### Composite Bindings - **Positive** (Button) - Description for the positive control binding. - **Negative** (Button) - Description for the negative control binding. ### Parameters on Axis Composite #### Parameters - **whichSideWins** (WhichSideWins) - Determines precedence when both positive and negative sides are actuated. - **minValue** (float) - The value returned when the negative side is actuated. Default is -1. - **maxValue** (float) - The value returned when the positive side is actuated. Default is 1. ### WhichSideWins Enum #### Values - **Neither** (0) - Neither side has precedence. Returns the midpoint value. - **Positive** (1) - The positive side has precedence. Returns `maxValue`. - **Negative** (2) - The negative side has precedence. Returns `minValue`. ``` -------------------------------- ### Get Touch Input Source: https://github.com/unity-technologies/inputsystem/wiki/OldVsNewInputSystem Access active touches on the touchscreen using `Touchscreen.current.activeTouches[i]`. This provides information about individual touch points. ```csharp Touchscreen.current.activeTouches[i] ``` -------------------------------- ### Query All Connected Devices Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Gamepad.md Use this to get a read-only list of all currently connected input devices without allocating memory. ```csharp InputSystem.devices ``` -------------------------------- ### Implement PlayerController with InputAction Source: https://context7.com/unity-technologies/inputsystem/llms.txt Demonstrates defining actions with bindings, subscribing to input callbacks, and using the polling API for movement and button interactions. ```csharp using UnityEngine; using UnityEngine.InputSystem; public class PlayerController : MonoBehaviour { // Create actions with bindings private InputAction moveAction; private InputAction jumpAction; private InputAction fireAction; void Awake() { // Simple action with single binding jumpAction = new InputAction("jump", binding: "/buttonSouth"); jumpAction.AddBinding("/space"); // Value action for continuous input (movement) moveAction = new InputAction("move", InputActionType.Value); moveAction.AddBinding("/leftStick"); moveAction.AddCompositeBinding("2DVector") .With("Up", "/w") .With("Down", "/s") .With("Left", "/a") .With("Right", "/d"); // Button action with interactions fireAction = new InputAction("fire", binding: "/rightTrigger"); fireAction.AddBinding("/leftButton"); // Subscribe to callbacks jumpAction.performed += ctx => Jump(); jumpAction.canceled += ctx => Debug.Log("Jump released"); moveAction.performed += ctx => Move(ctx.ReadValue()); moveAction.canceled += ctx => Move(Vector2.zero); fireAction.started += ctx => StartFiring(); fireAction.performed += ctx => Fire(); fireAction.canceled += ctx => StopFiring(); } void OnEnable() { moveAction.Enable(); jumpAction.Enable(); fireAction.Enable(); } void OnDisable() { moveAction.Disable(); jumpAction.Disable(); fireAction.Disable(); } void Update() { // Polling API alternative if (jumpAction.triggered) Jump(); Vector2 movement = moveAction.ReadValue(); transform.Translate(movement * Time.deltaTime * 5f); } void Jump() => Debug.Log("Jump!"); void Move(Vector2 direction) => Debug.Log($"Moving: {direction}"); void StartFiring() => Debug.Log("Fire started"); void Fire() => Debug.Log("Firing!"); void StopFiring() => Debug.Log("Fire stopped"); } ``` -------------------------------- ### Create Input Actions in Code Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Actions.md Manually instantiate and configure actions, action maps, and assets programmatically. ```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"); ``` -------------------------------- ### Using UnityEngine.InputSystem Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Workflow-Actions.md Include this using statement at the top of your C# script to access the Input System API. ```csharp using UnityEngine.InputSystem ``` -------------------------------- ### Add Multiple Controls to Composite Binding Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/ActionBindings.md This example demonstrates how to bind multiple controls to the same composite part, allowing for more flexible input mapping. ```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"); ``` -------------------------------- ### Registering a Custom Input Device Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Devices.md Use the InitializeOnLoad attribute and a static constructor to register a device layout, ensuring it is available in the Action editor. ```CSharp // Add the InitializeOnLoad attribute to automatically run the static // constructor of the class after each C# domain load. #if UNITY_EDITOR [InitializeOnLoad] #endif public class MyDevice : InputDevice, IInputUpdateCallbackReceiver { //... static MyDevice() { // RegisterLayout() adds a "Control layout" to the system. // These can be layouts for individual Controls (like sticks) // or layouts for entire Devices (which are themselves // Controls) like in our case. InputSystem.RegisterLayout(); } // You still need a way to trigger execution of the static constructor // in the Player. To do this, you can add the RuntimeInitializeOnLoadMethod // to an empty method. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] private static void InitializeInPlayer() {} } ``` -------------------------------- ### Implement Touch Handling with EnhancedTouch and Low-Level APIs Source: https://context7.com/unity-technologies/inputsystem/llms.txt Demonstrates the use of EnhancedTouch for multi-touch tracking, low-level Touchscreen access for primary touch, and TouchSimulation for testing. ```csharp using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.EnhancedTouch; using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch; public class TouchExample : MonoBehaviour { void OnEnable() { // Enable EnhancedTouch API (required for Touch.activeTouches) EnhancedTouchSupport.Enable(); } void OnDisable() { EnhancedTouchSupport.Disable(); } void Update() { // Using EnhancedTouch API (recommended) foreach (var touch in Touch.activeTouches) { Debug.Log($"Touch {touch.touchId}: {touch.screenPosition}, Phase: {touch.phase}"); switch (touch.phase) { case UnityEngine.InputSystem.TouchPhase.Began: OnTouchBegan(touch); break; case UnityEngine.InputSystem.TouchPhase.Moved: OnTouchMoved(touch); break; case UnityEngine.InputSystem.TouchPhase.Ended: OnTouchEnded(touch); break; } } // Access active fingers foreach (var finger in Touch.activeFingers) { Debug.Log($"Finger {finger.index}: {finger.currentTouch.screenPosition}"); } } void OnTouchBegan(Touch touch) { Debug.Log($"Touch began at {touch.startScreenPosition}"); } void OnTouchMoved(Touch touch) { Vector2 delta = touch.delta; Debug.Log($"Touch moved by {delta}"); } void OnTouchEnded(Touch touch) { // Check for tap if (touch.isTap) Debug.Log($"Tap detected! Count: {touch.tapCount}"); } } // Low-level Touchscreen access public class TouchscreenLowLevel : MonoBehaviour { void Update() { var touchscreen = Touchscreen.current; if (touchscreen == null) return; // Primary touch (drives Pointer representation) var primary = touchscreen.primaryTouch; if (primary.press.isPressed) { Vector2 pos = primary.position.ReadValue(); Debug.Log($"Primary touch at {pos}"); } // Access all touch slots foreach (var touch in touchscreen.touches) { if (touch.press.isPressed) Debug.Log($"Touch at {touch.position.ReadValue()}"); } } } // Touch simulation from mouse (for testing) public class TouchSimulationExample : MonoBehaviour { void OnEnable() { TouchSimulation.Enable(); } void OnDisable() { TouchSimulation.Disable(); } } ``` -------------------------------- ### Combine Bindings with Hold Modifier Source: https://github.com/unity-technologies/inputsystem/wiki/How-Do-I... Example of combining two input bindings with a hold modifier, requiring both to be active for a duration to trigger the action. ```C# var action = new InputAction(); action.AddBinding("//leftTrigger") .CombinedWith("//buttonSouth", modifiers: "hold(duration=0.4)"); ``` -------------------------------- ### Registering a Custom Device Layout Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/HID.md Use InputSystem.RegisterLayout within a static constructor to match devices via manufacturer strings or vendor/product IDs. The RuntimeInitializeOnLoadMethod attribute ensures the registration triggers during the player startup sequence. ```CSharp [InputControlLayout(stateType = typeof(DualShock4HIDInputReport)] #if UNITY_EDITOR [InitializeOnLoad] // Make sure static constructor is called during startup. #endif public DualShock4GamepadHID : Gamepad { static DualShock4GamepadHID() { // This is one way to match the device. InputSystem.RegisterLayout( new InputDeviceMatcher() .WithInterface("HID") .WithManufacturer("Sony.+Entertainment") .WithProduct("Wireless Controller")); // Alternatively, you can also match by PID and VID, which is generally // more reliable for HIDs. InputSystem.RegisterLayout( matches: new InputDeviceMatcher() .WithInterface("HID") .WithCapability("vendorId", 0x54C) // Sony Entertainment. .WithCapability("productId", 0x9CC)); // Wireless controller. } // In the Player, to trigger the calling of the static constructor, // create an empty method annotated with RuntimeInitializeOnLoadMethod. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void Init() {} } ``` -------------------------------- ### Define Control Paths Source: https://github.com/unity-technologies/inputsystem/blob/develop/Packages/com.unity.inputsystem/Documentation~/Controls.md Examples of path strings used to target specific devices, controls, or usage patterns within the Input System. ```csharp // Matches all gamepads (also gamepads *based* on the Gamepad layout): "" // Matches the "Submit" control on all devices: "*/" // Matches the key that prints the "a" character on the current keyboard layout: "/#(a)" // Matches the X axis of the left stick on a gamepad. "/leftStick/x" // Matches the orientation control of the right-hand XR controller: "/orientation" // Matches all buttons on a gamepad. "/