Class InputDevice | Package Manager UI website
docs.unity3d.com
    Show / Hide Table of Contents

    Class InputDevice

    Represents an input device which is always the root of a hierarchy of InputControl instances.

    Inheritance
    System.Object
    InputControl
    InputDevice
    Gamepad
    HID
    Joystick
    Keyboard
    Pointer
    Sensor
    OculusRemote
    OculusTrackingReference
    ViveLighthouse
    ViveTracker
    XRController
    XRHMD
    Inherited Members
    InputControl.name
    InputControl.displayName
    InputControl.shortDisplayName
    InputControl.path
    InputControl.layout
    InputControl.variants
    InputControl.device
    InputControl.parent
    InputControl.children
    InputControl.usages
    InputControl.aliases
    InputControl.stateBlock
    InputControl.noisy
    InputControl.synthetic
    InputControl.Item[String]
    InputControl.ToString()
    InputControl.EvaluateMagnitude()
    InputControl.EvaluateMagnitude(Void*)
    InputControl.WriteValueFromBufferIntoState(Void*, Int32, Void*)
    InputControl.WriteValueFromObjectIntoState(Object, Void*)
    InputControl.TryGetChildControl(String)
    InputControl.TryGetChildControl<TControl>(String)
    InputControl.GetChildControl(String)
    InputControl.GetChildControl<TControl>(String)
    InputControl.FinishSetup()
    InputControl.RefreshConfigurationIfNeeded()
    InputControl.RefreshConfiguration()
    InputControl.m_StateBlock
    InputControl.currentStatePtr
    InputControl.previousFrameStatePtr
    InputControl.defaultStatePtr
    InputControl.noiseMaskPtr
    InputControl.stateOffsetRelativeToDeviceRoot
    Namespace: UnityEngine.InputSystem
    Syntax
    public class InputDevice : InputControl
    Remarks

    Input devices act as the container for control hierarchies. Every hierarchy has to have a device at the root. Devices cannot occur as children of other controls.

    Devices are usually created automatically in response to hardware being discovered by the Unity runtime. However, it is possible to manually add devices using methods such as AddDevice<TDevice>(String).

    Add a "synthetic" gamepad that isn't actually backed by hardware:
    var gamepad = InputSystem.AddDevice<Gamepad>();

    There are subclasses representing the most common types of devices, like Mouse, Keyboard, Gamepad, and Touchscreen.

    To create your own types of devices, you can derive from InputDevice and register your device as a new "layout".

    Creating a custom type of input device.
    // 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;
    }

    Devices can have usages like any other control (usages). Unlike other controls, however, usages of InputDevices are allowed to be changed on the fly without requiring a change to the device layout (see SetDeviceUsage(InputDevice, String)).

    Constructors

    InputDevice()

    This constructor is public for the sake of Activator.CreateInstance only. To construct devices, use methods such as AddDevice<TDevice>(String). Manually using new on InputDevice will not result in a usable device.

    Declaration
    public InputDevice()

    Fields

    InvalidDeviceId

    Value of an invalid id.

    Declaration
    public const int InvalidDeviceId = 0
    Field Value
    Type Description
    System.Int32
    Remarks

    The input system will not assigned this ID to any device.

    Properties

    added

    Whether the device has been added to the system.

    Declaration
    public bool added { get; }
    Property Value
    Type Description
    System.Boolean
    Remarks

    Input devices can be constructed manually through UnityEngine.InputSystem.Layouts.InputDeviceBuilder. Also, they can be removed through RemoveDevice(InputDevice). This property reflects whether the device is currently added to the system.

    Note that devices in disconnectedDevices will all have this property return false.

    See Also
    AddDevice(InputDevice)
    devices

    all

    Return all input devices currently added to the system.

    Declaration
    public static ReadOnlyArray<InputDevice> all { get; }
    Property Value
    Type Description
    ReadOnlyArray<InputDevice>
    Remarks

    This is equivalent to devices.

    allControls

    A flattened list of controls that make up the device.

    Declaration
    public ReadOnlyArray<InputControl> allControls { get; }
    Property Value
    Type Description
    ReadOnlyArray<InputControl>
    Remarks

    Does not allocate.

    canRunInBackground

    If true, the device is capable of delivering input while the application is running in the background.

    Declaration
    public bool canRunInBackground { get; }
    Property Value
    Type Description
    System.Boolean
    Remarks

    Note that by default, even if capable of doing so, devices will not generate input while the application is not focused. To enable the behavior, use .

    description

    Metadata describing the device (product name etc.).

    Declaration
    public InputDeviceDescription description { get; }
    Property Value
    Type Description
    InputDeviceDescription
    Remarks

    The description of a device is unchanging over its lifetime and does not comprise data about a device's configuration (which is considered mutable).

    enabled

    Whether the device is currently enabled (i.e. sends and receives events).

    Declaration
    public bool enabled { get; }
    Property Value
    Type Description
    System.Boolean
    Remarks

    A device that is disabled will not receive events. I.e. events that are being sent to the device will be ignored.

    When disabling a native device, a DisableDeviceCommand will also be sent to the IInputRuntime. It depends on the specific runtime whether the device command is supported but if it is, the device will be disabled in the runtime and no longer send events. This is especially important for devices such as Sensor that incur both computation and battery consumption overhead while enabled.

    Specific types of devices can choose to start out in disabled state by default. This is generally the case for Sensor to ensure that their overhead is only incurred when actually being used by the application.

    See Also
    EnableDevice(InputDevice)
    DisableDevice(InputDevice)

    id

    Unique numeric ID for the device.

    Declaration
    public int id { get; }
    Property Value
    Type Description
    System.Int32
    Remarks

    This is only assigned once a device has been added to the system. No two devices will receive the same ID and no device will receive an ID that another device used before even if the device was removed. The only exception to this is if a device gets re-created as part of a layout change. For example, if a new layout is registered that replaces the Mouse layout, all Mouse devices will get recreated but will keep their existing device IDs.

    IDs are assigned by the input runtime.

    See Also
    AllocateDeviceId()

    lastUpdateTime

    Timestamp of last state event used to update the device.

    Declaration
    public double lastUpdateTime { get; }
    Property Value
    Type Description
    System.Double
    Remarks

    Events other than StateEvent and DeltaStateEvent will not cause lastUpdateTime to be changed.

    native

    Whether the device comes from the IInputRuntime

    Declaration
    public bool native { get; }
    Property Value
    Type Description
    System.Boolean
    Remarks

    Devices can be discovered when onDeviceDiscovered by the runtime or they can be added manually through the various AddDevice(InputDevice) APIs. Devices reported by the runtime will return true for this property whereas devices added manually will return false.

    Devices reported by the runtime will usually come from the Unity engine itself.

    See Also
    IInputRuntime
    onDeviceDiscovered

    remote

    Whether the device is mirrored from a remote input system and not actually present as a "real" device in the local system.

    Declaration
    public bool remote { get; }
    Property Value
    Type Description
    System.Boolean
    See Also
    remoting
    InputRemoting

    updateBeforeRender

    Whether the device requires an extra update before rendering.

    Declaration
    public bool updateBeforeRender { get; }
    Property Value
    Type Description
    System.Boolean
    Remarks

    The value of this property is determined by updateBeforeRender in the device's InputControlLayout.

    The extra update is necessary for tracking devices that are used in rendering code. For example, the eye transforms of an HMD should be refreshed right before rendering as refreshing only in the beginning of the frame will lead to a noticeable lag.

    See Also
    BeforeRender

    valueSizeInBytes

    Declaration
    public override int valueSizeInBytes { get; }
    Property Value
    Type Description
    System.Int32
    Overrides
    InputControl.valueSizeInBytes

    valueType

    Declaration
    public override Type valueType { get; }
    Property Value
    Type Description
    System.Type
    Overrides
    InputControl.valueType

    wasUpdatedThisFrame

    Declaration
    public bool wasUpdatedThisFrame { get; }
    Property Value
    Type Description
    System.Boolean

    Methods

    CompareValue(Void*, Void*)

    Declaration
    public override bool CompareValue(void *firstStatePtr, void *secondStatePtr)
    Parameters
    Type Name Description
    System.Void* firstStatePtr
    System.Void* secondStatePtr
    Returns
    Type Description
    System.Boolean
    Overrides
    InputControl.CompareValue(Void*, Void*)

    ExecuteCommand<TCommand>(ref TCommand)

    Declaration
    public long ExecuteCommand<TCommand>(ref TCommand command)
        where TCommand : struct, IInputDeviceCommandInfo
    Parameters
    Type Name Description
    TCommand command
    Returns
    Type Description
    System.Int64
    Type Parameters
    Name Description
    TCommand

    MakeCurrent()

    Make this the current device of its type.

    Declaration
    public virtual void MakeCurrent()
    Remarks

    Use this to set static properties that give fast access to the latest device used of a given type (current or leftHand and rightHand).

    This functionality is somewhat like a 'pwd' for the semantic paths but one where there can be multiple current working directories, one for each type.

    A device will be made current by the system initially when it is created and subsequently whenever it receives an event.

    OnAdded()

    Declaration
    protected virtual void OnAdded()

    OnRemoved()

    Declaration
    protected virtual void OnRemoved()

    ReadValueFromBufferAsObject(Void*, Int32)

    Declaration
    public override object ReadValueFromBufferAsObject(void *buffer, int bufferSize)
    Parameters
    Type Name Description
    System.Void* buffer
    System.Int32 bufferSize
    Returns
    Type Description
    System.Object
    Overrides
    InputControl.ReadValueFromBufferAsObject(Void*, Int32)

    ReadValueFromStateAsObject(Void*)

    Declaration
    public override object ReadValueFromStateAsObject(void *statePtr)
    Parameters
    Type Name Description
    System.Void* statePtr
    Returns
    Type Description
    System.Object
    Overrides
    InputControl.ReadValueFromStateAsObject(Void*)

    ReadValueFromStateIntoBuffer(Void*, Void*, Int32)

    Declaration
    public override void ReadValueFromStateIntoBuffer(void *statePtr, void *bufferPtr, int bufferSize)
    Parameters
    Type Name Description
    System.Void* statePtr
    System.Void* bufferPtr
    System.Int32 bufferSize
    Overrides
    InputControl.ReadValueFromStateIntoBuffer(Void*, Void*, Int32)

    Extension Methods

    InputControlExtensions.IsActuated(InputControl, Single)
    InputControlExtensions.ReadValueAsObject(InputControl)
    InputControlExtensions.ReadValueIntoBuffer(InputControl, Void*, Int32)
    InputControlExtensions.ReadDefaultValueAsObject(InputControl)
    InputControlExtensions.WriteValueFromObjectIntoEvent(InputControl, InputEventPtr, Object)
    InputControlExtensions.WriteValueIntoState(InputControl, Void*)
    InputControlExtensions.WriteValueIntoState<TValue>(InputControl, TValue, Void*)
    InputControlExtensions.WriteValueIntoEvent<TValue>(InputControl, TValue, InputEventPtr)
    InputControlExtensions.CheckStateIsAtDefault(InputControl)
    InputControlExtensions.CheckStateIsAtDefault(InputControl, Void*, Void*)
    InputControlExtensions.CheckStateIsAtDefaultIgnoringNoise(InputControl)
    InputControlExtensions.CheckStateIsAtDefaultIgnoringNoise(InputControl, Void*)
    InputControlExtensions.CompareStateIgnoringNoise(InputControl, Void*)
    InputControlExtensions.CompareState(InputControl, Void*, Void*, Void*)
    InputControlExtensions.CompareState(InputControl, Void*, Void*)
    InputControlExtensions.HasValueChangeInState(InputControl, Void*)
    InputControlExtensions.HasValueChangeInEvent(InputControl, InputEventPtr)
    InputControlExtensions.GetStatePtrFromStateEvent(InputControl, InputEventPtr)
    InputControlExtensions.FindControlsRecursive<TControl>(InputControl, IList<TControl>, Func<TControl, Boolean>)

    See Also

    InputControl
    Mouse
    Keyboard
    Gamepad
    Touchscreen
    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023