Reading new Input System inputs in C#

I’m trying to understand the easiest way to read inputs from the new Input System in code in a single class.

I want to read all the player input in a single class (called from within Update()) and then process it later down the line in Update() and FixedUpdate() respectively).

For instance, I would have something like this (just a simple pseudocode example) with the old input system:

    private Vector2 playerMovement = Vector2.zero;
    private bool playerAttacking = false;

    void GetPlayerInput()
    {
        playerMovement.x = Input.GetAxisRaw("Horizontal");
        playerMovement.y = Input.GetAxisRaw("Vertical");

        if (Input.GetKey("Attack"))
            playerAttacking = true;
        else
            playerAttacking = false;
    }

How do I implement something like this with the new Input System and which Behaviour (Send Messages, Broadcast Messages, Invoke Unity Events or Invoke C Sharp Events) would I need for it?

The two former ones all rely on multiple classes which is messy and not what I’m looking for (a single class to handle reading all input with a secondary class processing the player movement).

Then the Invoke Unity Events behaviour, although apparently suggested, relies almost entirely on Unity Editor side references which are very detached from the code side of the project, break easily (references) and just aren’t accessible through code properly.

That leaves me (as far as I understand the new Input System currently) only with the option to go for Invoke C Sharp Events. The Generate C# Class function generates a C# source file that seems to overtly complicate things by taking everything into account and none of the code or any examples I’ve been able to find online have suggested a way of doing things in a fashion similar to my code example above.

I might not be understanding the new Input System correctly, which is entirely possible as I’m just a hobbyist programmer, but I’m sure there must be some sort of a reasonably simple and robust way of just reading the status of the inputs based on their Action names.

Any help would be immensely appreciated, as the new Input System is still relatively new, especially in terms of available tutorials and documentation of clarity, thanks!

1 Like

Hi @Daedolon

There are a bunch of different ways to do this, which can definitely make it a little harder to get started. Here’s a simple, code-only, example to help:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    private Vector2 m_PlayerMovement;
    private InputAction m_MoveAction;
    private InputAction m_AttackAction;

    void Start()
    {
        m_MoveAction = new InputAction("Move");
        m_MoveAction.AddBinding("<Gamepad>/leftStick");
        m_MoveAction.Enable();

        m_AttackAction = new InputAction("Attack", binding: "<Gamepad>/buttonSouth");
        m_AttackAction.Enable();
    }

    void Update()
    {
        m_PlayerMovement = m_MoveAction.ReadValue<Vector2>();
        if(m_PlayerMovement != Vector2.zero)
            Debug.Log("Vector = " + m_PlayerMovement);
        
        var attacking = m_AttackAction.ReadValue<float>();
        if(Mathf.Approximately(attacking, 1f))
            Debug.Log("Attacking");
    }
}

You can get gradually more sophisticated from there. For example, you can define your input actions in an Input Action Asset in the editor and add a reference to the asset in your script. Then you can access the different actions using something like:

m_inputActions.FindAction("Move")

Input actions have methods like WasPressedThisFrame, WasReleasedThisFrame, and IsPressed to help you get closer to Input.GetKey functionality. If you’d rather get notified in a callback when an input event occurs, you can attach a callback handler to an input action like this:

m_MoveAction.performed += context =>
{
      m_PlayerMovement = context.ReadValue<Vector2>();
};

It sounds like you’re also using the PlayerInput class here. Note that this is really just a higher level wrapper around the concepts in this post (plus lots of extra goodies for local multiplayer games), so you don’t necessarily need it when getting started. That said, if you do want to use it, and you want a code-first approach, this is one way you could hook up event handlers to use Invoke C# Events behaviour:

GetComponent<PlayerInput>().onActionTriggered += context =>
{
      if(context.action == m_InputAsset.FindAction("Move"))
           m_PlayerMovement = context.ReadValue<Vector2>();
};

So basically, when the player triggers any of your input actions, the onActionTriggered handler will be called, and you can use the passed CallbackContext to figure out what action fired, and do whatever you need to in there.

Hope this helps

4 Likes

Might as well share because I was struggling a lot with this
(Note the PlayerInput component is added to a GameManager Object which is used as a Singleton, and this script would be on another object)

using UnityEngine;
using UnityEngine.InputSystem;


public class TestInput : MonoBehaviour
{
    private InputAction testAction;
    private PlayerInput playerInput;

    private void Awake()
    {
        //Getting the PlayerInput component
        playerInput = GameManager.instance.GetComponent<PlayerInput>();

        testAction = playerInput.actions.FindAction("Jump");
        testAction.performed += DoJumpAction;
    }

    private void OnEnable()
    {
        testAction.Enable();
    }

    private void OnDisable()
    {
        testAction.Disable();
    }

    void DoJumpAction(InputAction.CallbackContext context)
    {
        Debug.Log("JumpAction Success!!");
    }
}

Might not be the best way, but it works

1 Like