Home > Enterprise >  Cannot find/understand how to use the New Input System in Unity for my PlayerController script
Cannot find/understand how to use the New Input System in Unity for my PlayerController script

Time:10-20

I have this player controller script for a 2D top down game It uses the old input system but I want to use the newer one so that my game can support several input types (and also because I want to learn how to use the new input system)

I read the documentation on unity but still can't understand, I found this document enter image description here

then save it. Click on it and in inspector enable "Generate C# class". then in your code something like this:

private void Awake()
{
    InputActions playerInput = new InputActions();
    playerInput.GamePlayPlayer.Move.performed  = context => MoveInput(context);
    playerInput.Enable();
}

private void MoveInput(InputAction.CallbackContext context)
{
    Vector2 input = context.ReadValue<Vector2>();
    moveInputData = new Vector3(input.x, 0, input.y);
}
void Update()
{
    transform.position = Vector2.MoveTowards(transform.position, movePoint.position, moveSpeed * Time.deltaTime);

    if(moveInputData == Vector3.Zero)
        return;
        
    if (Vector2.Distance(transform.position, movePoint.position) <= .5f)
    {
        if (!Physics2D.OverlapCircle(movePoint.position   moveInputData, .2f, obstacleMask))
        {
            movePoint.position  = moveInputData;
        }
    }
}

I didn't test it, but I think it should be fine.

CodePudding user response:

You have setup the Control Schemes almost correctly, you need to change the Action Type to Value and Control Type to Vector2 or Stick, because you are getting two axes (up/down and left/right), like this:

enter image description here

Then you need to setup your scheme in the game, you need to add a Player Input component and select your Control Scheme:

enter image description here

Finally from your code you can access all the actions and action maps of your Control Scheme, in this case instead of reading a Horizontal and a Vertical axis you read them both like this:

InputActionAsset actions;

void Awake() {
    // Retrieve the action asset
    actions = GetComponent<PlayerInput>().actions;
}

void Update() {
    // Retrieve the current movement input (horizontal, vertical)
    // You can save this action in a variable in the Awake too if you plan to use it multiple times (like during each Update)
    Vector2 movement = actions.FindAction("Movement").ReadValue<Vector2>();

    // Check if we have horizontal movement
    if(movement.x != 0f){
        // Do stuff
    }

    // Check if we have vertical movement
    if(movement.y != 0f){
        // Do stuff
    }
}

Final note: I would avoid naming the Maps or Actions with a slash (/) in it, because you can retrieve actions from different maps like actions.FindAction("Music_Fight/Movement").

  • Related