Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Get reference to an InputAction by action name

Discussion in 'Input System' started by DaveTheCoder, Dec 10, 2020.

  1. DaveTheCoder

    DaveTheCoder

    Joined:
    Feb 26, 2020
    Posts:
    10
    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?
     
    Novack likes this.
  2. Xavierseal

    Xavierseal

    Joined:
    Oct 31, 2016
    Posts:
    7
    InputActionAsset[string actionName] should do the job for you.

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

    DaveTheCoder

    Joined:
    Feb 26, 2020
    Posts:
    10
    Thanks. I'll try that.

    I used a different approach, which works, based on another forum thread. I'll post the details later.
     
    Last edited: Dec 13, 2020
    Xavierseal likes this.
  4. DaveTheCoder

    DaveTheCoder

    Joined:
    Feb 26, 2020
    Posts:
    10
    Xavierseal, I couldn't get that code to compile.

    The approach I used was:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.InputSystem;
    3.  
    4. public class Player : MonoBehaviour {
    5. ...
    6.     public float speed = 3.5f;
    7. ...
    8.     private bool movingForward = false;
    9. ...
    10.     private MyControl _gameActions;
    11.     private InputAction _forwardAction;
    12. ...
    13.     private void Awake()
    14.     {
    15.         _gameActions = new MyControl();
    16.         _forwardAction = _gameActions.Player.Forward;
    17. ...
    18.         _forwardAction.performed += context => movingForward = true;
    19.         _forwardAction.canceled  += context => movingForward = false;
    20. ...
    21.     }
    22. ...
    23.     void Update() {
    24. ...
    25.        if (movingForward) {
    26.           transform.position += transform.forward * speed * Time.deltaTime;
    27.        }
    28. ...
    29.     }
    30. ...
    31. ...
    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.
     
    Last edited: Dec 14, 2020
    Xavierseal likes this.
  5. Xavierseal

    Xavierseal

    Joined:
    Oct 31, 2016
    Posts:
    7
    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.
     
    rubendariohh and WiseAX like this.