Class InputSystem
This is the central hub for the input system.
Inheritance
Namespace: UnityEngine.InputSystem
Syntax
public static class InputSystem
Remarks
This class has the central APIs for working with the input system. You can manage devices available in the system (AddDevice<TDevice>(String), devices, onDeviceChange and related APIs) or extend the input system with custom functionality (RegisterLayout<T>(String, Nullable<InputDeviceMatcher>), RegisterInteraction<T>(String), RegisterProcessor<T>(String), RegisterBindingComposite<T>(String), and related APIs).
To control haptics globally, you can use PauseHaptics(), ResumeHaptics(), and ResetHaptics().
To enable and disable individual devices (such as Sensor devices), you can use EnableDevice(InputDevice) and DisableDevice(InputDevice).
The input system is initialized as part of Unity starting up. It is generally safe to call the APIs here from any of Unity's script callbacks.
Note that, like most Unity APIs, most of the properties and methods in this API can only be called on the main thread. However, select APIs like QueueEvent(InputEventPtr) can be called from threads. Where this is the case, it is stated in the documentation.
Properties
devices
The list of currently connected devices.
Declaration
public static ReadOnlyArray<InputDevice> devices { get; }
Property Value
Type | Description |
---|---|
ReadOnlyArray<InputDevice> |
Remarks
Note that accessing this property does not allocate. It gives read-only access directly to the system's internal array of devices.
The value returned by this property should not be held on to. When the device setup in the system changes, any value previously returned by this property may become invalid. Query the property directly whenever you need it.
disconnectedDevices
Devices that have been disconnected but are retained by the input system in case they are plugged back in.
Declaration
public static ReadOnlyArray<InputDevice> disconnectedDevices { get; }
Property Value
Type | Description |
---|---|
ReadOnlyArray<InputDevice> |
Remarks
During gameplay it is undesirable to have the system allocate and release managed memory as devices are unplugged and plugged back in as it would ultimately lead to GC spikes during gameplay. To avoid that, input devices that have been reported by the IInputRuntime and are removed through DeviceRemoveEvent are retained by the system and then reused if the device is plugged back in.
Note that the devices moved to disconnected status will still see a Removed notification and a Added notification when plugged back in.
To determine if a newly discovered device is one we have seen before, the system uses a simple approach of comparing InputDeviceDescription. Note that there can be errors and a device may be incorrectly classified as Reconnected when in fact it is a different device from before. The problem is that based on information made available by platforms, it can be inherently difficult to determine whether a device is indeed the very same one.
For example, it is often not possible to determine with 100% certainty whether an identical looking device to one we've previously seen on a different USB port is indeed the very same device. OSs will usually reattach a USB device to its previous instance if it is plugged into the same USB port but create a new instance of the same device is plugged into a different port.
For devices that do relay their serial the matching is reliable.
The list can be purged by calling
Note that if you call RemoveDevice(InputDevice) explicitly, the given device is not retained by the input system and will not appear on this list.
Also note that devices on this list will be lost when domain reloads happen in the editor (i.e. on script recompilation and when entering play mode).
See Also
metrics
Declaration
public static InputMetrics metrics { get; }
Property Value
Type | Description |
---|---|
InputMetrics |
pollingFrequency
Frequency at which devices that need polling are being queried in the background.
Declaration
public static float pollingFrequency { get; set; }
Property Value
Type | Description |
---|---|
System.Single |
Remarks
Input data is gathered from platform APIs either as events or polled periodically.
In the former case, where we get input as events, the platform is responsible for monitoring input devices and accumulating their state changes which the input runtime then periodically queries and sends off as InputEvent.
In the latter case, where input has to be explicitly polled from the system, the input runtime will periodically sample the state of input devices and send it off as input events. Wherever possible, this happens in the background at a fixed frequency. The pollingFrequency property controls the rate at which the sampling happens.
The unit is Hertz. A value of 120, for example, means that devices are sampled 120 times per second.
The default polling frequency is 60 Hz.
For devices that are polled, the frequency setting will directly translate to changes in the time patterns. At 60 Hz, for example, timestamps for a specific, polled device will be spaced at roughly 1/60th of a second apart.
Note that it depends on the platform which devices are polled (if any). On Win32, for example, only XInput gamepads are polled.
Also note that the polling frequency applies to all devices that are polled. It is not possible to set polling frequency on a per-device basis.
remoting
The local InputRemoting instance which can mirror local input to a remote input system or can make input in a remote system available locally.
Declaration
public static InputRemoting remoting { get; }
Property Value
Type | Description |
---|---|
InputRemoting |
Remarks
In the editor, this is always initialized. In players, this will be null if remoting is disabled (which it is by default in release players).
settings
The current configuration of the input system.
Declaration
public static InputSettings settings { get; set; }
Property Value
Type | Description |
---|---|
InputSettings |
Remarks
The input system can be configured on a per-project basis. Settings can either be created and installed on the fly or persisted as assets in the project.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException | Value is null when setting the property. |
version
The current version of the input system package.
Declaration
public static Version version { get; }
Property Value
Type | Description |
---|---|
System.Version |
Methods
AddDevice(String, String, String)
Add a new device by instantiating the given device layout.
Declaration
public static InputDevice AddDevice(string layout, string name = null, string variants = null)
Parameters
Type | Name | Description |
---|---|---|
System.String | layout | Name of the layout to instantiate. Must be a device layout. Note that layout names are case-insensitive. |
System.String | name | Name to assign to the device. If null, the layout name is used instead. Note that device names are made unique automatically by the system by appending numbers to them (e.g. "gamepad", "gamepad1", "gamepad2", etc.). |
System.String | variants | Semicolon-separated list of layout variants to use for the device. |
Returns
Type | Description |
---|---|
InputDevice | The newly created input device. |
Remarks
Note that adding a device to the system will allocate and also create garbage on the GC heap.
Examples
InputSystem.AddDevice("Gamepad");
AddDevice(InputDevice)
Declaration
public static void AddDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device |
AddDevice(InputDeviceDescription)
Declaration
public static InputDevice AddDevice(InputDeviceDescription description)
Parameters
Type | Name | Description |
---|---|---|
InputDeviceDescription | description |
Returns
Type | Description |
---|---|
InputDevice | The newly created device that has been added to devices. |
Remarks
Exceptions
Type | Condition |
---|---|
System.ArgumentException | No layout can be found that matches the given device |
AddDevice<TDevice>(String)
Add a new device by instantiating the layout registered for type TDevice
.
Declaration
public static TDevice AddDevice<TDevice>(string name = null)
where TDevice : InputDevice
Parameters
Type | Name | Description |
---|---|---|
System.String | name | Name to give to the device. If null, a default name will be given to the device (usually based on the name of its layout). Note that if a device with the same name already exists, a number will be appended to the name. |
Returns
Type | Description |
---|---|
TDevice | The newly added device. |
Type Parameters
Name | Description |
---|---|
TDevice | Type of device to add. |
Remarks
The device will be added to the devices list and a notification on onDeviceChange will be triggered.
// Add a gamepad.
InputSystem.AddDevice<Gamepad>();
Exceptions
Type | Condition |
---|---|
System.InvalidOperationException | Instantiating the layout for |
AddDeviceUsage(InputDevice, String)
Add a usage tag to the given device.
Declaration
public static void AddDeviceUsage(InputDevice device, string usage)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to add the usage to. |
System.String | usage | New usage to add to the device. |
Remarks
Usages allow to "tag" a specific device such that the tag can then be used in lookups and bindings. A common use is for identifying the handedness of an XRController but the usages can be arbitrary strings.
This method adds a new usage to the device's set of usages. If the device already has the given usage, the method does nothing. To instead set the device's usages to a single one, use SetDeviceUsage(InputDevice, String). To remove usages from a device, call RemoveDeviceUsage(InputDevice, String).
The set of usages a device has can be queried with usages (a device is an InputControl and thus, like controls, has an associated set of usages).
If the set of usages on the device changes as a result of calling this method, onDeviceChange will be triggered with UsageChanged.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.ArgumentException |
|
See Also
AddDeviceUsage(InputDevice, InternedString)
Add a usage tag to the given device.
Declaration
public static void AddDeviceUsage(InputDevice device, InternedString usage)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to add the usage to. |
InternedString | usage | New usage to add to the device. |
Remarks
Usages allow to "tag" a specific device such that the tag can then be used in lookups and bindings. A common use is for identifying the handedness of an XRController but the usages can be arbitrary strings.
This method adds a new usage to the device's set of usages. If the device already has the given usage, the method does nothing. To instead set the device's usages to a single one, use SetDeviceUsage(InputDevice, InternedString). To remove usages from a device, call RemoveDeviceUsage(InputDevice, InternedString).
The set of usages a device has can be queried with usages (a device is an InputControl and thus, like controls, has an associated set of usages).
If the set of usages on the device changes as a result of calling this method, onDeviceChange will be triggered with UsageChanged.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.ArgumentException |
|
See Also
DisableAllEnabledActions()
Disable all actions (and implicitly all action sets) that are currently enabled.
Declaration
public static void DisableAllEnabledActions()
See Also
DisableDevice(InputDevice)
Disable the given device, i.e. "mute" it.
Declaration
public static void DisableDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to disable. If already disabled, the method will do nothing. |
Remarks
A disabled device will not receive input and will remain in its default state. It will remain present in the system but without actually feeding input into it.
Disabling devices is most useful for Sensor devices on battery-powered platforms where having a sensor enabled will increase energy consumption. Sensors will usually start out in disabled state and can be enabled, when needed, with EnableDevice(InputDevice) and disabled again wth this method.
However, disabling a device can be useful in other situations, too. For example, when simulating input (say, mouse input) locally from a remote source, it can be desirable to turn off the respective local device.
To remove a device altogether, use RemoveDevice(InputDevice) instead. This will not only silence input but remove the InputDevice instance from the system altogether.
See Also
EnableDevice(InputDevice)
Re-enable the given device.
Declaration
public static void EnableDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to enable. If already enabled, the method will do nothing. |
Remarks
This can be used after a device has been disabled with DisableDevice(InputDevice) or with devices that start out in disabled state (usually the case for all Sensor devices).
When enabled, a device will receive input when available.
// Enable the gyroscope, if present.
if (Gyroscope.current != null)
InputSystem.EnableDevice(Gyroscope.current);
See Also
FindControls(String)
Find all controls that match the given InputControlPath.
Declaration
public static InputControlList<InputControl> FindControls(string path)
Parameters
Type | Name | Description |
---|---|---|
System.String | path |
Returns
Type | Description |
---|---|
InputControlList<InputControl> |
Examples
// Find all gamepads (literally: that use the "Gamepad" layout).
InputSystem.FindControls("<Gamepad>");
// Find all sticks on all gamepads.
InputSystem.FindControls("<Gamepad>/*stick");
// Same but filter stick by type rather than by name.
InputSystem.FindControls<StickControl>("<Gamepad>/*");
See Also
FindControls<TControl>(String)
Declaration
public static InputControlList<TControl> FindControls<TControl>(string path)
where TControl : InputControl
Parameters
Type | Name | Description |
---|---|---|
System.String | path |
Returns
Type | Description |
---|---|
InputControlList<TControl> |
Type Parameters
Name | Description |
---|---|
TControl |
FindControls<TControl>(String, ref InputControlList<TControl>)
Declaration
public static int FindControls<TControl>(string path, ref InputControlList<TControl> controls)
where TControl : InputControl
Parameters
Type | Name | Description |
---|---|---|
System.String | path | |
InputControlList<TControl> | controls |
Returns
Type | Description |
---|---|
System.Int32 |
Type Parameters
Name | Description |
---|---|
TControl |
GetDevice(String)
Declaration
public static InputDevice GetDevice(string nameOrLayout)
Parameters
Type | Name | Description |
---|---|---|
System.String | nameOrLayout |
Returns
Type | Description |
---|---|
InputDevice |
GetDevice<TDevice>()
Declaration
public static TDevice GetDevice<TDevice>()
where TDevice : InputDevice
Returns
Type | Description |
---|---|
TDevice |
Type Parameters
Name | Description |
---|---|
TDevice |
GetDevice<TDevice>(String)
Declaration
public static TDevice GetDevice<TDevice>(string usage)
where TDevice : InputDevice
Parameters
Type | Name | Description |
---|---|---|
System.String | usage |
Returns
Type | Description |
---|---|
TDevice |
Type Parameters
Name | Description |
---|---|
TDevice |
GetDevice<TDevice>(InternedString)
Return the device of the given type TDevice
that has the
given usage assigned. Returns null if no such device currently exists.
Declaration
public static TDevice GetDevice<TDevice>(InternedString usage)
where TDevice : InputDevice
Parameters
Type | Name | Description |
---|---|---|
InternedString | usage | Usage of the device, e.g. "LeftHand". |
Returns
Type | Description |
---|---|
TDevice | The device with the given type and usage or null. |
Type Parameters
Name | Description |
---|---|
TDevice | Type of device to look for. |
Remarks
Devices usages are most commonly employed to "tag" devices for a specific role.
A common scenario, for example, is to distinguish which hand a specific XRController
is associated with. However, arbitrary usages can be assigned to devices.
// Get the left hand XRController.
var leftHand = InputSystem.GetDevice<XRController>(CommonUsages.leftHand);
// Mark gamepad #2 as being for player 1.
InputSystem.SetDeviceUsage(Gamepad.all[1], "Player1");
// And later look it up.
var player1Gamepad = InputSystem.GetDevice<Gamepad>(new InternedString("Player1"));
See Also
GetDeviceById(Int32)
Look up a device by its unique ID.
Declaration
public static InputDevice GetDeviceById(int deviceId)
Parameters
Type | Name | Description |
---|---|---|
System.Int32 | deviceId | Unique ID of device. Such as given by deviceId. |
Returns
Type | Description |
---|---|
InputDevice | The device for the given ID or null if no device with the given ID exists (or no longer exists). |
Remarks
Device IDs are not reused in a given session of the application (or Unity editor).
See Also
GetUnsupportedDevices()
Return the list of devices that have been reported by the IInputRuntime but could not be matched to any known InputControlLayout.
Declaration
public static List<InputDeviceDescription> GetUnsupportedDevices()
Returns
Type | Description |
---|---|
System.Collections.Generic.List<InputDeviceDescription> | A list of descriptions of devices that could not be recognized. |
Remarks
If new layouts are added to the system or if additional InputDeviceMatcher are added to existing layouts, devices in this list may appear or disappear.
See Also
GetUnsupportedDevices(List<InputDeviceDescription>)
Declaration
public static int GetUnsupportedDevices(List<InputDeviceDescription> descriptions)
Parameters
Type | Name | Description |
---|---|---|
System.Collections.Generic.List<InputDeviceDescription> | descriptions |
Returns
Type | Description |
---|---|
System.Int32 |
ListEnabledActions()
Return a list of all the actions that are currently enabled in the system.
Declaration
public static List<InputAction> ListEnabledActions()
Returns
Type | Description |
---|---|
System.Collections.Generic.List<InputAction> | A new list instance containing all currently enabled actions. |
Remarks
To avoid allocations, use ListEnabledActions(List<InputAction>).
See Also
ListEnabledActions(List<InputAction>)
Add all actions that are currently enabled in the system to the given list.
Declaration
public static int ListEnabledActions(List<InputAction> actions)
Parameters
Type | Name | Description |
---|---|---|
System.Collections.Generic.List<InputAction> | actions | List to add actions to. |
Returns
Type | Description |
---|---|
System.Int32 | The number of actions added to the list. |
Remarks
If the capacity of the given list is large enough, this method will not allocate memory.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
ListInteractions()
Declaration
public static IEnumerable<string> ListInteractions()
Returns
Type | Description |
---|---|
System.Collections.Generic.IEnumerable<System.String> |
ListLayouts()
Return a list with the names of all layouts that have been registered.
Declaration
public static List<string> ListLayouts()
Returns
Type | Description |
---|---|
System.Collections.Generic.List<System.String> | A list of layout names. |
See Also
ListLayouts(List<String>)
Add the names of all layouts that have been registered to the given list.
Declaration
public static int ListLayouts(List<string> list)
Parameters
Type | Name | Description |
---|---|---|
System.Collections.Generic.List<System.String> | list | List to add the layout names to. |
Returns
Type | Description |
---|---|
System.Int32 | The number of names added to |
Remarks
If the capacity of the given list is large enough, this method will not allocate.
ListLayoutsBasedOn(String)
Declaration
public static List<string> ListLayoutsBasedOn(string baseLayout)
Parameters
Type | Name | Description |
---|---|---|
System.String | baseLayout |
Returns
Type | Description |
---|---|
System.Collections.Generic.List<System.String> |
ListLayoutsBasedOn(String, List<String>)
Declaration
public static int ListLayoutsBasedOn(string baseLayout, List<string> list)
Parameters
Type | Name | Description |
---|---|---|
System.String | baseLayout | |
System.Collections.Generic.List<System.String> | list |
Returns
Type | Description |
---|---|
System.Int32 |
ListProcessors()
Declaration
public static IEnumerable<string> ListProcessors()
Returns
Type | Description |
---|---|
System.Collections.Generic.IEnumerable<System.String> |
LoadLayout(String)
Try to load a layout instance.
Declaration
public static InputControlLayout LoadLayout(string name)
Parameters
Type | Name | Description |
---|---|---|
System.String | name | Name of the layout to load. Note that layout names are case-insensitive. |
Returns
Type | Description |
---|---|
InputControlLayout | The constructed layout instance or null if no layout of the given name could be found. |
LoadLayout<TControl>()
Declaration
public static InputControlLayout LoadLayout<TControl>()
where TControl : InputControl
Returns
Type | Description |
---|---|
InputControlLayout |
Type Parameters
Name | Description |
---|---|
TControl |
PauseHaptics()
Pause haptic effect playback on all devices.
Declaration
public static void PauseHaptics()
Remarks
Calls PauseHaptics() on all InputDevice that implement the interface.
Examples
// When going into the menu from gameplay, pause haptics.
gameplayControls.backAction.onPerformed +=
ctx =>
{
gameplayControls.Disable();
menuControls.Enable();
InputSystem.PauseHaptics();
};
See Also
QueueConfigChangeEvent(InputDevice, Double)
Queue a DeviceConfigurationEvent that signals that the configuration of the given device has changed and that cached configuration will thus have to be refreshed.
Declaration
public static void QueueConfigChangeEvent(InputDevice device, double time = -1)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device whose configuration has changed. |
System.Double | time | Timestamp for the event. If not supplied, the current time will be used. |
Remarks
All state of an input device that is not input or output state is considered its "configuration".
A simple example is keyboard layouts. A Keyboard will typically have an associated keyboard layout that dictates the function of each key and which can be changed by the user at the system level. In the input system, the current keyboard layout can be queried via keyboardLayout. When the layout changes at the system level, the input backend sends a configuration change event to signal that the configuration of the keyboard has changed and that cached data may be outdated. In response, Keyboard will flush out cached information such as the name of the keyboard layout and display names (displayName) of individual keys which causes them to be fetched again from the backend the next time they are accessed.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.InvalidOperationException |
|
QueueDeltaStateEvent<TDelta>(InputControl, TDelta, Double)
Queue a DeltaStateEvent to update part of the input state of the given device.
Declaration
public static void QueueDeltaStateEvent<TDelta>(InputControl control, TDelta delta, double time = -1)
where TDelta : struct
Parameters
Type | Name | Description |
---|---|---|
InputControl | control | Control on a device to update state of. |
TDelta | delta | New state for the control. Type of state must match the state of the control. |
System.Double | time |
Type Parameters
Name | Description |
---|---|
TDelta |
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.InvalidOperationException | |
System.ArgumentException |
QueueEvent(InputEventPtr)
Add an event to the internal event queue.
Declaration
public static void QueueEvent(InputEventPtr eventPtr)
Parameters
Type | Name | Description |
---|---|---|
InputEventPtr | eventPtr | Event to add to the internal event buffer. |
Remarks
The event will be copied in full to the internal event buffer meaning that
you can release memory for the event after it has been queued. The internal event
buffer is flushed on the next input system update (see Update()).
Note that if timeslicing is in effect (see
// Queue an input event on the first gamepad.
var gamepad = Gamepad.all[0];
using (StateEvent.From(gamepad, out var eventPtr))
{
gamepad.leftStick.WriteValueIntoEvent(new Vector2(0.123, 0.234), eventPtr);
InputSystem.QueueEvent(eventPtr);
}
Exceptions
Type | Condition |
---|---|
System.ArgumentException |
|
See Also
QueueEvent<TEvent>(ref TEvent)
Declaration
public static void QueueEvent<TEvent>(ref TEvent inputEvent)
where TEvent : struct, IInputEventTypeInfo
Parameters
Type | Name | Description |
---|---|---|
TEvent | inputEvent |
Type Parameters
Name | Description |
---|---|
TEvent |
QueueStateEvent<TState>(InputDevice, TState, Double)
Queue a StateEvent to update the input state of the given device.
Declaration
public static void QueueStateEvent<TState>(InputDevice device, TState state, double time = -1)
where TState : struct, IInputStateTypeInfo
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device whose input state to update |
TState | state | |
System.Double | time | Timestamp for the event. If not supplied, the current time is used. Note
that if the given time is in the future and timeslicing is active ( |
Type Parameters
Name | Description |
---|---|
TState | Type of input state, such as MouseState. Must match the expected
type of state of |
Remarks
The given state must match exactly what is expected by the given device. If unsure, an alternative
is to grab the state as an event directly from the device using
// Allocates temporary, unmanaged memory for the event.
// using statement automatically disposes the memory once we have queued the event.
using (StateEvent.From(Mouse.current, out var eventPtr))
{
// Use controls on mouse to write values into event.
Mouse.current.position.WriteValueIntoEvent(new Vector(123, 234), eventPtr);
// Queue event.
InputSystem.QueueEvent(eventPtr);
}
The event will only be queued and not processed right away. This means that the state of
device
will not change immediately as a result of calling this method. Instead,
the event will be processed as part of the next input update.
Note that this method updates the complete input state of the device including all of its
controls. To update just part of the state of a device, you can use QueueDeltaStateEvent<TDelta>(InputControl, TDelta, Double)
(however, note that there are some restrictions; see documentation).
InputSystem.QueueStateEvent(Mouse.current, new MouseState { position = new Vector(123, 234) });
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.InvalidOperationException |
|
System.ArgumentException |
QueueTextEvent(InputDevice, Char, Double)
Queue a TextEvent on the given device.
Declaration
public static void QueueTextEvent(InputDevice device, char character, double time = -1)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to queue the event on. |
System.Char | character | Text character to input through the event. |
System.Double | time | Optional event time stamp. If not supplied, the current time will be used. |
Remarks
Text input is sent to devices character by character. This allows sending strings of arbitrary length without necessary incurring GC overhead.
For the event to have any effect on device
, the device must
implement ITextInputReceiver. It will see OnTextInput(Char)
being called when the event is processed.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.InvalidOperationException |
|
See Also
RegisterBindingComposite(Type, String)
Declaration
public static void RegisterBindingComposite(Type type, string name)
Parameters
Type | Name | Description |
---|---|---|
System.Type | type | |
System.String | name |
RegisterBindingComposite<T>(String)
Declaration
public static void RegisterBindingComposite<T>(string name = null)
Parameters
Type | Name | Description |
---|---|---|
System.String | name |
Type Parameters
Name | Description |
---|---|
T |
RegisterInteraction(Type, String)
Declaration
public static void RegisterInteraction(Type type, string name = null)
Parameters
Type | Name | Description |
---|---|---|
System.Type | type | |
System.String | name |
RegisterInteraction<T>(String)
Declaration
public static void RegisterInteraction<T>(string name = null)
Parameters
Type | Name | Description |
---|---|---|
System.String | name |
Type Parameters
Name | Description |
---|---|
T |
RegisterLayout(String, String, Nullable<InputDeviceMatcher>)
Register a layout in JSON format.
Declaration
public static void RegisterLayout(string json, string name = null, InputDeviceMatcher? matches = default(InputDeviceMatcher? ))
Parameters
Type | Name | Description |
---|---|---|
System.String | json | JSON data describing the layout. |
System.String | name | Optional name of the layout. If null or empty, the name is taken from the "name" property of the JSON data. If it is supplied, it will override the "name" property if present. If neither is supplied, an System.ArgumentException is thrown. |
System.Nullable<InputDeviceMatcher> | matches |
Remarks
The JSON format makes it possible to create new device and control layouts completely in data. They have to ultimately be based on a layout backed by a C# type, however (e.g. Gamepad).
Note that most errors in layouts will only be detected when instantiated (i.e. when a device or control is being created from a layout). The JSON data will, however, be parsed once on registration to check for a device description in the layout. JSON format errors will thus be detected during registration.
InputSystem.RegisterLayout(@"
{
""name"" : ""MyDevice"",
""controls"" : [
{
""name"" : ""myButton"",
""layout"" : ""Button""
}
]
}
);
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.ArgumentException | No name has been supplied either through |
See Also
RegisterLayout(Type, String, Nullable<InputDeviceMatcher>)
Register a control layout based on a type.
Declaration
public static void RegisterLayout(Type type, string name = null, InputDeviceMatcher? matches = default(InputDeviceMatcher? ))
Parameters
Type | Name | Description |
---|---|---|
System.Type | type | Type to derive a control layout from. Must be derived from InputControl. |
System.String | name | Name to use for the layout. If null or empty, the short name of the type ( |
System.Nullable<InputDeviceMatcher> | matches | Optional device description. If this is supplied, the layout will automatically be instantiated for newly discovered devices that match the description. |
Remarks
When the layout is instantiated, the system will reflect on all public fields and properties of the type which have a value type derived from InputControl or which are annotated with InputControlAttribute.
The type can be annotated with InputControlLayoutAttribute for additional options but the attribute is not necessary for a type to be usable as a control layout.
// InputControlLayoutAttribute attribute is only necessary if you want
// to override default behavior that occurs when registering your device
// as a layout.
// The most common use of InputControlLayoutAttribute is to direct the system
// to a custom "state struct" through the `stateType` property. See below for details.
[InputControlLayout(displayName = "My Device", stateType = typeof(MyDeviceState))]
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class MyDevice : InputDevice
{
public ButtonControl button { get; private set; }
public AxisControl axis { get; private set; }
// Register the device.
static MyDevice()
{
// In case you want instance of your device to automatically be created
// when specific hardware is detected by the Unity runtime, you have to
// add one or more "device matchers" (InputDeviceMatcher) for the layout.
// These matchers are compared to an InputDeviceDescription received from
// the Unity runtime when a device is connected. You can add them either
// using InputSystem.RegisterLayoutMatcher() or by directly specifying a
// matcher when registering the layout.
InputSystem.RegisterLayout<MyDevice>(
// For the sake of demonstration, let's assume your device is a HID
// and you want to match by PID and VID.
matches: new InputDeviceMatcher()
.WithInterface("HID")
.WithCapability("PID", 1234)
.WithCapability("VID", 5678));
}
// This is only to trigger the static class constructor to automatically run
// in the player.
[RuntimeInitializeOnLoadMethod]
private static void InitializeInPlayer() {}
protected override void FinishSetup()
{
base.FinishSetup();
button = GetChildControl<ButtonControl>("button");
axis = GetChildControl<AxisControl>("axis");
}
}
// A "state struct" describes the memory format used a device. Each device can
// receive and store memory in its custom format. InputControls are then connected
// the individual pieces of memory and read out values from them.
[StructLayout(LayoutKind.Explicit, Size = 32)]
public struct MyDeviceState : IInputStateTypeInfo
{
// In the case of a HID (which we assume for the sake of this demonstration),
// the format will be "HID". In practice, the format will depend on how your
// particular device is connected and fed into the input system.
// The format is a simple FourCC code that "tags" state memory blocks for the
// device to give a base level of safety checks on memory operations.
public FourCC format => return new FourCC('H', 'I', 'D');
// InputControlAttributes on fields tell the input system to create controls
// for the public fields found in the struct.
// Assume a 16bit field of buttons. Create one button that is tied to
// bit #3 (zero-based). Note that buttons do not need to be stored as bits.
// They can also be stored as floats or shorts, for example.
[InputControl(name = "button", layout = "Button", bit = 3)]
public ushort buttons;
// Create a floating-point axis. The name, if not supplied, is taken from
// the field.
[InputControl(layout = "Axis")]
public short axis;
}
Note that if matches
is supplied and there are devices that could not
have been recognized yet, the matcher will be immediately matched against these devices
and any match will result in an input device being created (except if the layout happens
to be suppressed via supportedDevices).
See StickControl or Gamepad for examples of layouts.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
RegisterLayout<T>(String, Nullable<InputDeviceMatcher>)
Register a type as a control layout.
Declaration
public static void RegisterLayout<T>(string name = null, InputDeviceMatcher? matches = default(InputDeviceMatcher? ))
where T : InputControl
Parameters
Type | Name | Description |
---|---|---|
System.String | name | Name to use for the layout. If null or empty, the short name of the type will be used. |
System.Nullable<InputDeviceMatcher> | matches | Optional device description. If this is supplied, the layout will automatically be instantiated for newly discovered devices that match the description. |
Type Parameters
Name | Description |
---|---|
T | Type to derive a control layout from. |
Remarks
This method is equivalent to calling RegisterLayout(Type, String, Nullable<InputDeviceMatcher>) with
typeof(T)
.
See Also
RegisterLayoutBuilder(Expression<Func<InputControlLayout>>, String, String, Nullable<InputDeviceMatcher>)
Register a builder that delivers an InputControlLayout instance on demand.
Declaration
public static void RegisterLayoutBuilder(Expression<Func<InputControlLayout>> builderExpression, string name, string baseLayout = null, InputDeviceMatcher? matches = default(InputDeviceMatcher? ))
Parameters
Type | Name | Description |
---|---|---|
Expression<System.Func<InputControlLayout>> | builderExpression | |
System.String | name | |
System.String | baseLayout | |
System.Nullable<InputDeviceMatcher> | matches |
Remarks
The given expression must be a lambda expression solely comprised of a method call with no arguments. Can be static or instance method call. If it is an instance method, the instance object must be serializable.
The reason for these restrictions and for not taking an arbitrary delegate is that we need to be able to persist the layout builder between domain reloads.
Note that the layout that is being constructed must not vary over time (except between domain reloads).
Examples
[Serializable]
class MyLayoutBuilder
{
public InputControlLayout Build()
{
var builder = new InputControlLayout.Builder()
.WithType<MyDevice>();
builder.AddControl("button1").WithLayout("Button");
return builder.Build();
}
}
var builder = new MyLayoutBuilder();
InputSystem.RegisterLayoutBuilder(() => builder.Build(), "MyLayout");
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException | |
System.ArgumentException |
RegisterLayoutMatcher(String, InputDeviceMatcher)
Add an additional device matcher to an existing layout.
Declaration
public static void RegisterLayoutMatcher(string layoutName, InputDeviceMatcher matcher)
Parameters
Type | Name | Description |
---|---|---|
System.String | layoutName | Name of the device layout that should be instantiated if |
InputDeviceMatcher | matcher | Specification to match against InputDeviceDescription instances. |
Remarks
Each device layout can have zero or more matchers associated with it. If any one of the matchers matches a given InputDeviceDescription (MatchPercentage(InputDeviceDescription)) better than any other matcher (for the same or any other layout), then the given layout will be used for the discovered device.
See Also
RegisterLayoutMatcher<TDevice>(InputDeviceMatcher)
Declaration
public static void RegisterLayoutMatcher<TDevice>(InputDeviceMatcher matcher)
where TDevice : InputDevice
Parameters
Type | Name | Description |
---|---|---|
InputDeviceMatcher | matcher |
Type Parameters
Name | Description |
---|---|
TDevice |
RegisterLayoutOverride(String, String)
Register a layout that applies overrides to one or more other layouts.
Declaration
public static void RegisterLayoutOverride(string json, string name = null)
Parameters
Type | Name | Description |
---|---|---|
System.String | json | Layout in JSON format. |
System.String | name | Optional name of the layout. If null or empty, the name is taken from the "name" property of the JSON data. If it is supplied, it will override the "name" property if present. If neither is supplied, an System.ArgumentException is thrown. |
Remarks
Layout overrides are layout pieces that are applied on top of existing layouts. This can be used to modify any layout in the system non-destructively. The process works the same as extending an existing layout except that instead of creating a new layout by merging the derived layout and the base layout, the overrides are merged directly into the base layout.
Layouts used as overrides look the same as normal layouts and have the same format. The only difference is that they are explicitly registered as overrides.
Note that unlike "normal" layouts, layout overrides have the ability to extend multiple base layouts.
RegisterProcessor(Type, String)
Register an InputProcessor<TValue> with the system.
Declaration
public static void RegisterProcessor(Type type, string name = null)
Parameters
Type | Name | Description |
---|---|---|
System.Type | type | Type that implements InputProcessor<TValue>. |
System.String | name | Name to use for the processor. If null or empty, name will be taken from short name
of |
Remarks
Processors are used by both bindings (see InputBinding) and by controls (see InputControl) to post-process input values as they are being requested from calls such as ReadValue<TValue>() or ReadValue().
See Also
RegisterProcessor<T>(String)
Declaration
public static void RegisterProcessor<T>(string name = null)
Parameters
Type | Name | Description |
---|---|---|
System.String | name |
Type Parameters
Name | Description |
---|---|
T |
RemoveDevice(InputDevice)
Remove a device from the system such that it no longer receives input and is no longer part of the set of devices in devices.
Declaration
public static void RemoveDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to remove. If the device has already been removed (i.e. if added is false), the method does nothing. |
Remarks
Actions that are bound to controls on the device will automatically unbind when the device is removed.
When a device is removed, onDeviceChange will be triggered with Removed. The device will be removed from devices as well as from any device-specific getters such as all.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
See Also
RemoveDeviceUsage(InputDevice, String)
Remove a usage tag from the given device.
Declaration
public static void RemoveDeviceUsage(InputDevice device, string usage)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to remove the usage from. |
System.String | usage | Usage to remove from the device. |
Remarks
This method removes an existing usage from the given device. If the device does not have the given usage tag, the method does nothing. Use SetDeviceUsage(InputDevice, String) or AddDeviceUsage(InputDevice, String) to add usages to a device.
The set of usages a device has can be queried with usages (a device is an InputControl and thus, like controls, has an associated set of usages).
If the set of usages on the device changes as a result of calling this method, onDeviceChange will be triggered with UsageChanged.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.ArgumentException |
|
See Also
RemoveDeviceUsage(InputDevice, InternedString)
Remove a usage tag from the given device.
Declaration
public static void RemoveDeviceUsage(InputDevice device, InternedString usage)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to remove the usage from. |
InternedString | usage | Usage to remove from the device. |
Remarks
This method removes an existing usage from the given device. If the device does not have the given usage tag, the method does nothing. Use SetDeviceUsage(InputDevice, InternedString) or AddDeviceUsage(InputDevice, InternedString) to add usages to a device.
The set of usages a device has can be queried with usages (a device is an InputControl and thus, like controls, has an associated set of usages).
If the set of usages on the device changes as a result of calling this method, onDeviceChange will be triggered with UsageChanged.
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
System.ArgumentException |
|
See Also
RemoveDisconnectedDevices()
Purge all disconnected devices from disconnectedDevices.
Declaration
public static void RemoveDisconnectedDevices()
Remarks
This will release all references held on to for these devices or any of their controls and will allow the devices to be reclaimed by the garbage collector.
See Also
RemoveLayout(String)
Remove an already registered layout from the system.
Declaration
public static void RemoveLayout(string name)
Parameters
Type | Name | Description |
---|---|---|
System.String | name | Name of the layout to remove. Note that layout names are case-insensitive. |
Remarks
Note that removing a layout also removes all devices that directly or indirectly use the layout.
This method can be used to remove both control or device layouts.
ResetHaptics()
Stop haptic effect playback on all devices.
Declaration
public static void ResetHaptics()
Remarks
Will reset haptics effects on all devices to their default state.
Calls ResetHaptics() on all InputDevice that implement the interface.
ResumeHaptics()
Resume haptic effect playback on all devices.
Declaration
public static void ResumeHaptics()
Remarks
Calls ResumeHaptics() on all InputDevice that implement the interface.
See Also
SetDeviceUsage(InputDevice, String)
Set the usage tag of the given device to usage
.
Declaration
public static void SetDeviceUsage(InputDevice device, string usage)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to set the usage on. |
System.String | usage | New usage for the device. |
Remarks
Usages allow to "tag" a specific device such that the tag can then be used in lookups and bindings. A common use is for identifying the handedness of an XRController but the usages can be arbitrary strings.
This method either sets the usages of the device to a single string (meaning it will
clear whatever, if any usages, the device has when the method is called) or,
if usage
is null or empty, resets the usages of the device
to be empty. To add to a device's set of usages, call AddDeviceUsage(InputDevice, String).
To remove usages from a device, call RemoveDeviceUsage(InputDevice, String).
The set of usages a device has can be queried with usages (a device is an InputControl and thus, like controls, has an associated set of usages).
// Tag a gamepad to be associated with player #1.
InputSystem.SetDeviceUsage(myGamepad, "Player1");
// Create an action that binds to player #1's gamepad specifically.
var action = new InputAction(binding: "<Gamepad>{Player1}/buttonSouth");
// Move the tag from one gamepad to another.
InputSystem.SetDeviceUsage(myGamepad, null); // Clears usages on 'myGamepad'.
InputSystem.SetDeviceUsage(otherGamepad, "Player1");
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
See Also
SetDeviceUsage(InputDevice, InternedString)
Set the usage tag of the given device to usage
.
Declaration
public static void SetDeviceUsage(InputDevice device, InternedString usage)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | Device to set the usage on. |
InternedString | usage | New usage for the device. |
Remarks
Usages allow to "tag" a specific device such that the tag can then be used in lookups and bindings. A common use is for identifying the handedness of an XRController but the usages can be arbitrary strings.
This method either sets the usages of the device to a single string (meaning it will
clear whatever, if any usages, the device has when the method is called) or,
if usage
is null or empty, resets the usages of the device
to be empty. To add to a device's set of usages, call AddDeviceUsage(InputDevice, InternedString).
To remove usages from a device, call RemoveDeviceUsage(InputDevice, InternedString).
The set of usages a device has can be queried with usages (a device is an InputControl and thus, like controls, has an associated set of usages).
If the set of usages on the device changes as a result of calling this method, onDeviceChange will be triggered with UsageChanged.
// Tag a gamepad to be associated with player #1.
InputSystem.SetDeviceUsage(myGamepad, new InternedString("Player1"));
// Create an action that binds to player #1's gamepad specifically.
var action = new InputAction(binding: "<Gamepad>{Player1}/buttonSouth");
// Move the tag from one gamepad to another.
InputSystem.SetDeviceUsage(myGamepad, null); // Clears usages on 'myGamepad'.
InputSystem.SetDeviceUsage(otherGamepad, new InternedString("Player1"));
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException |
|
See Also
TryFindMatchingLayout(InputDeviceDescription)
Try to match a description for an input device to a layout.
Declaration
public static string TryFindMatchingLayout(InputDeviceDescription deviceDescription)
Parameters
Type | Name | Description |
---|---|---|
InputDeviceDescription | deviceDescription | Description of an input device. |
Returns
Type | Description |
---|---|
System.String | Name of the layout that has been matched to the given description or null if no matching layout was found. |
Remarks
Layouts are matched by the InputDeviceDescription they were registered with (if any).
The fields in a layout's device description are considered regular expressions which are matched
against the values supplied in the given deviceDescription
.
Examples
var layoutName = InputSystem.TryFindMatchingLayout(
new InputDeviceDescription
{
product = "Xbox Wired Controller",
manufacturer = "Microsoft"
}
);
TryGetBindingComposite(String)
Declaration
public static Type TryGetBindingComposite(string name)
Parameters
Type | Name | Description |
---|---|---|
System.String | name |
Returns
Type | Description |
---|---|
System.Type |
TryGetInteraction(String)
Declaration
public static Type TryGetInteraction(string name)
Parameters
Type | Name | Description |
---|---|---|
System.String | name |
Returns
Type | Description |
---|---|
System.Type |
TryGetProcessor(String)
Declaration
public static Type TryGetProcessor(string name)
Parameters
Type | Name | Description |
---|---|---|
System.String | name |
Returns
Type | Description |
---|---|
System.Type |
TryResetDevice(InputDevice)
Declaration
public static bool TryResetDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device |
Returns
Type | Description |
---|---|
System.Boolean |
TrySyncDevice(InputDevice)
Declaration
public static bool TrySyncDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device |
Returns
Type | Description |
---|---|
System.Boolean |
Update()
Run a single update of input state.
Declaration
public static void Update()
Remarks
Except in tests and when using ProcessEventsManually, this method should not normally be called. The input system will automatically update as part of the player loop as determined by updateMode. Calling this method is equivalent to inserting extra frames.
When using ProcessEventsInDynamicUpdate TODO
When using Manual, this method MUST be called for input to update in the player. Not calling the method as part of the player loop may result in excessive memory consumption and potential loss of input.
Each update will flush out buffered input events and cause them to be processed. This in turn will update the state of input devices (InputDevice) and trigger actions (InputAction) that monitor affected device state.
See Also
Events
onActionChange
Event that is signalled when the state of enabled actions in the system changes or when actions are triggered.
Declaration
public static event Action<object, InputActionChange> onActionChange
Event Type
Type | Description |
---|---|
System.Action<System.Object, InputActionChange> |
Remarks
The object received by the callback is either an InputAction or an InputActionMap depending on whether the InputActionChange affects a single action or an entire action map.
Examples
InputSystem.onActionChange +=
(obj, change) =>
{
if (change == InputActionChange.ActionPerformed)
{
var action = (InputAction)obj;
var control = action.lastTriggerControl; TODO this is missing now
....
}
};
onAfterUpdate
Event that is fired after the input system has completed an update and processed all pending events.
Declaration
public static event Action onAfterUpdate
Event Type
Type | Description |
---|---|
System.Action |
See Also
onBeforeUpdate
Event that is fired before the input system updates.
Declaration
public static event Action onBeforeUpdate
Event Type
Type | Description |
---|---|
System.Action |
Remarks
The input system updates in sync with player loop and editor updates. Input updates
are run right before the respective script update. For example, an input update for
Dynamic is run before MonoBehaviour.Update
methods
are executed.
The update callback itself is triggered before the input system runs its own update and before it flushes out its event queue. This means that events queued from a callback will be fed right into the upcoming update.
See Also
onDeviceChange
Event that is signalled when the device setup in the system changes.
Declaration
public static event Action<InputDevice, InputDeviceChange> onDeviceChange
Event Type
Type | Description |
---|---|
System.Action<InputDevice, InputDeviceChange> |
Remarks
This can be used to detect when devices are added or removed as well as detecting when existing devices change their configuration.
Examples
InputSystem.onDeviceChange +=
(device, change) =>
{
switch (change)
{
case InputDeviceChange.Added:
Debug.Log("Device added: " + device);
break;
case InputDeviceChange.Removed:
Debug.Log("Device removed: " + device);
break;
case InputDeviceChange.ConfigurationChanged:
Debug.Log("Device configuration changed: " + device);
break;
}
};
onDeviceCommand
Event that is signalled when a InputDeviceCommand is sent to an InputDevice.
Declaration
public static event InputDeviceCommandDelegate onDeviceCommand
Event Type
Type | Description |
---|---|
InputDeviceCommandDelegate |
Remarks
This can be used to intercept commands and optionally handle them without them reaching the IInputRuntime.
The first delegate in the list that returns a result other than null
is considered
to have handled the command. If a command is handled by a delegate in the list, it will
not be sent on to the runtime.
See Also
onEvent
Declaration
public static event Action<InputEventPtr, InputDevice> onEvent
Event Type
Type | Description |
---|---|
System.Action<InputEventPtr, InputDevice> |
onFindLayoutForDevice
Event that is signalled when the system is trying to match a layout to a device it has discovered.
Declaration
public static event InputDeviceFindControlLayoutDelegate onFindLayoutForDevice
Event Type
Type | Description |
---|---|
InputDeviceFindControlLayoutDelegate |
Remarks
This event allows customizing the layout discovery process and to generate
layouts on the fly, if need be. The system will invoke callbacks with the
name of the layout it has matched (or null
if it couldn't find any
matching layout to the device based on the current layout setup. If all
the callbacks return null
, that layout will be instantiated. If,
however, any of the callbacks returns a new name instead, the system will use that
layout instead.
To generate layouts on the fly, register them with the system in the callback and then return the name of the newly generated layout from the callback.
Note that this callback will also be invoked if the system could not match any
existing layout to the device. In that case, the matchedLayout
argument
to the callback will be null
.
Callbacks also receive a device ID and reference to the input runtime. For devices where more information has to be fetched from the runtime in order to generate a layout, this allows issuing DeviceCommand(Int32, InputDeviceCommand*) calls for the device. Note that for devices that are not coming from the runtime (i.e. devices created directly in script code), the device ID will be InvalidDeviceId.
Examples
InputSystem.onFindLayoutForDevice +=
(deviceId, description, matchedLayout, runtime) =>
{
////TODO: complete example
};
onLayoutChange
Event that is signalled when the layout setup in the system changes.
Declaration
public static event Action<string, InputControlLayoutChange> onLayoutChange
Event Type
Type | Description |
---|---|
System.Action<System.String, InputControlLayoutChange> |
Remarks
First parameter is the name of the layout that has changed and second parameter is the type of change that has occurred.
InputSystem.onLayoutChange +=
(name, change) =>
{
switch (change)
{
case InputControlLayoutChange.Added:
Debug.Log($"New layout {name} has been added");
break;
case InputControlLayoutChange.Removed:
Debug.Log($"Layout {name} has been removed");
break;
case InputControlLayoutChange.Replaced:
Debug.Log($"Layout {name} has been updated");
break;
}
}
See Also
onSettingsChange
Event that is triggered if any of the properties in settings changes or if settings is replaced entirely with a new InputSettings object.
Declaration
public static event Action onSettingsChange
Event Type
Type | Description |
---|---|
System.Action |