IndieGame/client/Packages/com.unity.inputsystem@1.7.0/Documentation~/Migration.md
DOBEST\zhaoyingjie f242607587 初始化工程
2024-10-11 10:12:15 +08:00

22 KiB

uid
input-system-migration

Migrating from the old input system

This guide provides a list of APIs in UnityEngine.Input (and other related APIs in UnityEngine) and their corresponding APIs in the new Input System. Not all APIs have a corresponding version in the new API yet.

Note

: All of the new APIs are in the UnityEngine.InputSystem namespace. The namespace is omitted here for brevity. UnityEngine.InputSystem is referenced in full for easy disambiguation.

Note that it is possible to have code for the old and the new input system at the same time using conditional compilation. When the new input system is enabled in the player preferences (see here), the ENABLE_INPUT_SYSTEM preprocessor directive is available.

#if ENABLE_INPUT_SYSTEM
    // New input system backends are enabled.
#endif

#if ENABLE_LEGACY_INPUT_MANAGER
    // Old input backends are enabled.
#endif

    // NOTE: Both can be true at the same time as it is possible to select "Both"
    //       under "Active Input Handling".

UnityEngine.Input

UnityEngine.Input.acceleration

Use Accelerometer.current.acceleration.ReadValue().

UnityEngine.Input.accelerationEventCount

See UnityEngine.Input.accelerationEvents.

UnityEngine.Input.accelerationEvents

Acceleration events aren't made available separately from other input events. The following code traces all input events on the Accelerometer.current device.

    private InputEventTrace trace;

    void StartTrace()
    {
        InputSystem.EnableDevice(Accelerometer.current);

        trace = new InputEventTrace(Accelerometer.current);
        trace.Enable();
    }

    void Update()
    {
        foreach (var e in trace)
        {
            //...
        }
        trace.Clear();
    }

UnityEngine.Input.anyKey

Use InputSystem.onAnyButtonPress.

InputSystem.onAnyButtonPress
    .CallOnce(ctrl => Debug.Log($"Button {ctrl} pressed!"));

UnityEngine.Input.anyKeyDown

Use Keyboard.current.anyKey.wasUpdatedThisFrame

UnityEngine.Input.backButtonLeavesApp

No corresponding API yet.

UnityEngine.Input.compass

No corresponding API yet.

UnityEngine.Input.compensateSensors

Use InputSystem.settings.compensateForScreenOrientation.

UnityEngine.Input.compositionCursorPos

Use Keyboard.current.SetIMECursorPosition(myPosition).

UnityEngine.Input.compositionString

Subscribe to the Keyboard.onIMECompositionChange event:

    var compositionString = "";
    Keyboard.current.onIMECompositionChange += composition =>
    {
        compositionString = composition.ToString();
    };

UnityEngine.Input.deviceOrientation

No corresponding API yet.

UnityEngine.Input.gyro

The UnityEngine.Gyroscope class is replaced by multiple separate sensor Devices in the new Input System:

UnityEngine.Input.gyro.attitude

Use AttitudeSensor.current.orientation.ReadValue().

UnityEngine.Input.gyro.enabled

// Get:
Gyroscope.current.enabled

// Set:
InputSystem.EnableDevice(Gyroscope.current);
InputSystem.DisableDevice(Gyroscope.current);

Note

: The new Input System replaces UnityEngine.Gyroscope with multiple separate sensor devices. Substitute Gyroscope with other sensors in the sample as needed. See UnityEngine.Input.gyro section for details.

UnityEngine.Input.gyro.gravity

Use GravitySensor.current.gravity.ReadValue().

UnityEngine.Input.gyro.rotationRate

Use Gyroscope.current.angularVelocity.ReadValue().

UnityEngine.Input.gyro.rotationRateUnbiased

No corresponding API yet.

UnityEngine.Input.gyro.updateInterval

Use Sensor.samplingFrequency:

Gyroscope.current.samplingFrequency = 1.0f / updateInterval;

Note

:

UnityEngine.Input.gyro.userAcceleration

Use LinearAccelerationSensor.current.acceleration.acceleration.ReadValue().

UnityEngine.Input.imeCompositionMode

No corresponding API yet.

UnityEngine.Input.imeIsSelected

// Get:
Keyboard.current.imeSelected

// Set:
Keyboard.current.SetIMEEnabled(true);

UnityEngine.Input.inputString

Subscribe to the Keyboard.onTextInput event:

Keyboard.current.onTextInput +=
    character => /* ... */;

UnityEngine.Input.location

No corresponding API yet.

UnityEngine.Input.mousePosition

Use Mouse.current.position.ReadValue().

Note

: Mouse simulation from touch isn't implemented yet.

UnityEngine.Input.mousePresent

Use Mouse.current != null.

UnityEngine.Input.multiTouchEnabled

No corresponding API yet.

UnityEngine.Input.simulateMouseWithTouches

No corresponding API yet.

UnityEngine.Input.stylusTouchSupported

No corresponding API yet.

UnityEngine.Input.touchCount

Use InputSystem.EnhancedTouch.Touch.activeTouches.Count

Note

: Enable enhanced touch support first by calling InputSystem.EnhancedTouchSupport.Enable().

UnityEngine.Input.touches

Use InputSystem.EnhancedTouch.Touch.activeTouches.

Note

: Enable enhanced touch support first by calling InputSystem.EnhancedTouch.Enable().

UnityEngine.Input.touchPressureSupported

No corresponding API yet.

UnityEngine.Input.touchSupported

Use Touchscreen.current != null.

UnityEngine.Input.GetAccelerationEvent

See UnityEngine.Input.accelerationEvents.

UnityEngine.Input.GetAxis

There is no global setup that corresponds exactly to virtual axis setups in the old Input Manager settings. Instead, you can create sets of Input Actions as independent Assets, or put them directly on your C# components.

For example, if you want to recreate the following axis configuration:

Fire1 Action in Old Input Manager

Option A: Put Input Actions on your component

  1. Declare one or more fields of type InputAction.

        public class MyComponent : MonoBehaviour
        {
            public InputAction fireAction;
    
  2. Configure a response to the Action.

            void Awake()
            {
                fireAction.performed += ctx => Fire();
            }
    
            void Fire()
            {
                //...
            }
    
  3. Put the component on a GameObject. You can now configure Bindings in the Inspector window. Click the plus sign on the Bindings list to add Bindings, and double-click the Bindings to pick Controls to bind to.

    MyComponent fireAction

  4. Enable and disable the Action as needed.

            void OnEnable()
            {
                fireAction.Enable();
            }
    
            void OnDisable()
            {
                fireAction.Disable();
            }
    

Option B: Create an Input Action Asset

  1. Create an Input Action Asset (right-click in the Project browser and select Create > Input Actions). Give the Asset a name.

  2. Double-click the Asset to open the Input Actions editor window.

  3. In the Action Maps column, click the plus sign to add a new Action Map.

  4. Double-click the New Action Map name to rename the set. Use a descriptive name, such as gameplay.

  5. In the Actions column, click the plus sign to add a new Action.

  6. Double-click the Action to give it a name.

  7. Add Bindings to the Action. To do this, click the plus sign on the Action and choose a Binding type from the list.

  8. Select the Binding and click on the Path button in the right column to pick Controls to bind to.

  9. Click Save Asset. Your Input Action editor should now look like this:

    MyControls.inputactions

  10. Check the Generate C# Wrapper Class checkbox in the Inspector window for the Asset, then click Apply. Your Inspector should now look like this:

MyControls.inputactions

  1. Add an instance of the generated C# wrapper class to your component.
public class MyComponent : MonoBehaviour
{
    MyControls controls;
  1. Create the instance and hook up a response to the fire Action.
    public void Awake()
    {
        controls = new MyControls();
        controls.gameplay.fire.performed += ctx => Fire();
    }
  1. Enable and disable the Action as appropriate.
    public void OnEnable()
    {
        controls.Enable();
    }

    public void OnDisable()
    {
        controls.Disable();
    }

Hints

  • To force button-like behavior on the control referenced in a Binding, add a press Interaction to it.
  • You can access the Control that triggered an Action from the callback. Through it, you can also query its current value.
    fireAction.performed +=
        ctx =>
        {
            var control = ctx.control; // Grab control.
            var value = ctx.GetValue<float>(); // Read value from control.
    
            // Can do control-specific checks.
            var button = control as ButtonControl;
            if (button != null && button.wasPressedThisFrame)
                /* ... */;
        }
    

UnityEngine.Input.GetAxisRaw

Not directly applicable. You can use InputControl<>.ReadUnprocessedValue() to read unprocessed values from any control.

UnityEngine.Input.GetButton

Use InputAction.IsPressed.

if (playerInput.actions["fire"].IsPressed() && Time.time - m_LastFireTime >= kFireRate)
    Fire();

UnityEngine.input.GetButtonDown

Use InputAction.WasPressedThisFrame.

if (playerInput.actions["fire"].WasPressedThisFrame())
    Fire();

UnityEngine.input.GetButtonUp

Use InputAction.WasReleasedThisFrame.

if (playerInput.actions["fire"].WasReleasedThisFrame())
    StopFiring();

UnityEngine.Input.GetJoystickNames

There is no API that corresponds to this exactly.

Here are various ways to discover connected Devices:

// Query a list of all connected Devices (does not allocate; read-only access).
InputSystem.devices

// Get notified when a Device is added or removed.
InputSystem.onDeviceChange +=
    (device, change) =>
    {
        if (change == InputDeviceChange.Added || change == InputDeviceChange.Removed)
        {
            Debug.Log($"Device '{device}' was {change}");
        }
    }

// Find all gamepads and joysticks.
var devices = InputSystem.devices;
for (var i = 0; i < devices.Count; ++i)
{
    var device = devices[i];
    if (device is Joystick || device is Gamepad)
    {
        Debug.Log("Found " + device);
    }
}

UnityEngine.Input.GetKey

Use ButtonControl.isPressed on the corresponding key:

// Using KeyControl property directly.
Keyboard.current.spaceKey.isPressed
Keyboard.current.aKey.isPressed // etc.

// Using Key enum.
Keyboard.current[Key.Space].isPressed

// Using key name.
((KeyControl)Keyboard.current["space"]).isPressed

Note

: The Input System identifies keys by physical layout, not according to the current language mapping of the keyboard. To query the name of the key according to the language mapping, use KeyControl.displayName.

UnityEngine.Input.GetKeyDown

Use ButtonControl.wasPressedThisFrame on the corresponding key:

// Using KeyControl property directly.
Keyboard.current.spaceKey.wasPressedThisFrame
Keyboard.current.aKey.wasPressedThisFrame // etc.

// Using Key enum.
Keyboard.current[Key.Space].wasPressedThisFrame

// Using key name.
((KeyControl)Keyboard.current["space"]).wasPressedThisFrame

Note

: The Input System identifies keys by physical layout, not according to the current language mapping of the keyboard. To query the name of the key according to the language mapping, use KeyControl.displayName.

UnityEngine.Input.GetKeyUp

Use ButtonControl.wasReleasedThisFrame on the corresponding key:

// Using KeyControl property directly.
Keyboard.current.spaceKey.wasReleasedThisFrame
Keyboard.current.aKey.wasReleasedThisFrame // etc.

// Using Key enum.
Keyboard.current[Key.Space].wasReleasedThisFrame

// Using key name.
((KeyControl)Keyboard.current["space"]).wasReleasedThisFrame

Note

: The Input System identifies keys by physical layout, not according to the current language mapping of the keyboard. To query the name of the key according to the language mapping, use KeyControl.displayName.

UnityEngine.Input.GetMouseButton

Use ButtonControl.isPressed on the corresponding mouse button:

Mouse.current.leftButton.isPressed
Mouse.current.rightButton.isPressed
Mouse.current.middleButton.isPressed

// You can also go through all buttons on the mouse (does not allocate).
var controls = Mouse.current.allControls;
for (var i = 0; i < controls.Count; ++i)
{
    var button = controls[i] as ButtonControl;
    if (button != null && button.isPressed)
        /* ... */;
}

// Or look up controls by name.
((ButtonControl)Mouse.current["leftButton"]).isPressed

UnityEngine.Input.GetMouseButtonDown

Use ButtonControl.wasPressedThisFrame on the corresponding mouse button:

Mouse.current.leftButton.wasPressedThisFrame
Mouse.current.rightButton.wasPressedThisFrame
Mouse.current.middleButton.wasPressedThisFrame

UnityEngine.Input.GetMouseButtonUp

Use ButtonControl.wasReleasedThisFrame on the corresponding mouse button:

Mouse.current.leftButton.wasReleasedThisFrame
Mouse.current.rightButton.wasReleasedThisFrame
Mouse.current.middleButton.wasReleasedThisFrame

UnityEngine.Input.GetTouch

Use InputSystem.EnhancedTouch.Touch.activeTouches[i]

Note

: Enable enhanced touch support first by calling InputSystem.EnhancedTouch.Enable().

UnityEngine.Input.IsJoystickPreconfigured

Not needed. Devices which derive from Gamepad always correctly implement the mapping of axes and buttons to the corresponding InputControl members of the Gamepad class.

UnityEngine.Input.ResetInputAxes

Not directly applicable.

UnityEngine.TouchScreenKeyboard

No corresponding API yet. Use TouchScreenKeyboard for now.