Convert "If Input.GetAxis" via New Input System

Implementing the new input system over the old and the code is something like “If Input.GetAxis(Attack) && enemy != null”, how would I write If They press attack && enemly == null then reduce their health etc. with the new input system?

Thanks!

Also

controls.Player.Jump.performed += ctx => JumpKey();

I have this code, but it allows the player to infinetly jump so maybe 2 birds one stone on this post, how would I stop it? It ignores the !=jumping bool code that worked with the old input system

I’ve moved your post to Scripting because it has nothing to do with 2D.

1 Like

The new input system primarily works with delegates/callbacks. You assign the methods into the callbacks, and do any further checks in them.

public class InputExample : Monobehaviour
{
    private InputMaster inputMaster = new InputMaster(); //this is whatever your input asset class is
   
    private void Awake()
    {
        inputMaster.Enable();
        inputMaster.Player.Attack.performed += Attack;
        inputMaster.Player.Jump.performed += Jump;
    }
   
    private void Attack(CallbackContext ctx)
    {
        if (enemy != null)
        {
            //stuff
        }
    }
   
    private void Jump(CallbackContext ctx)
    {
        if (!jumping)
        {
            //jump here
        }
    }
}

Not a complete example but it should give you an idea of how to structure things. Namely, it’s not a drop in replacement with the old system.

1 Like

Actually I Think I see what you did, the ctx is in the void’s themselves and not in the awake? (as I had controls.Player.Jump.performed += ctx => JumpKey(); In the awake) and using Jump; not JumpKey? I’m confused as I watched Brackey’s video on this and that’s where I based my code off
https://www.youtube.com/watch?v=p-3S73MaDP8

Edit: I tried doing this in my code and it did not work… it says stuff about CallbackContext not existing, then if I change it to InputMaster.CallbackContext ctx, then it would

Assets\Scripts\Player.cs(39,43): error CS7036: There is no argument given that corresponds to the required formal parameter ‘ctx’ of ‘Player.JumpKey(InputAction.CallbackContext)’

Assets\Scripts\Player.cs(39,9): error CS0029: Cannot implicitly convert type ‘void’ to ‘System.Action<UnityEngine.InputSystem.InputAction.CallbackContext>’

The documentation really wants us to use it that way, yes. However, it supports polling-based approaches just as well, too.

Once you have a reference to your InputAction, check this out:

It can be a lot closer than the example given, though. I did, in fact, do an almost-drop-in-replacement in a very large project recently.

To get as close to being a drop-in replacement as you reasonably can, use a centralised action map, use the option to generate a C# class and keep a reference to a single instance of that (e.g. in a Singleton), then use the methods mentioned above.