Get reference to an InputAction by action name

In a script, how do you obtain a reference to an InputAction, using the name of the action that's specified in the Editor's Input Action Asset dialog?

1 Like

InputActionAsset[string actionName] should do the job for you.

InputAction jumpAction = playerInput.actions["Jump"];

4 Likes

Thanks. I'll try that.

I used a different approach, which works, based on another forum thread. I'll post the details later.

1 Like

Xavierseal, I couldn't get that code to compile.

The approach I used was:

using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour {
...
    public float speed = 3.5f;
...
    private bool movingForward = false;
...
    private MyControl _gameActions;
    private InputAction _forwardAction;
...
    private void Awake()
    {
        _gameActions = new MyControl();
        _forwardAction = _gameActions.Player.Forward;
...
        _forwardAction.performed += context => movingForward = true;
        _forwardAction.canceled  += context => movingForward = false;
...
    }
...
    void Update() {
...
       if (movingForward) {
          transform.position += transform.forward * speed * Time.deltaTime;
       }
...
    }
...
...

where:
"MyControl" is the name of the Input Actions asset.
"Player" is the name of the map within the asset.
"Forward" is the name of the action within the map.

I used the C# script generated from the asset to help me figure out those names.

2 Likes

If you want to my way, you would need a reference field for the PlayerInput component.
Generating C# code could be a convenient way, but for me I usually find it less flexible.
Just do what works for you best.

2 Likes