Search code examples
c#unity-game-enginegame-development

Unity Input System Movement


I get this error: InvalidOperationException: Cannot read value of type 'Vector2' from control '/Keyboard/w' bound to action 'Player/Movement[/Keyboard/w,/Keyboard/a,/Keyboard/s,/Keyboard/d]' (control is a 'KeyControl' with value type 'float')

and also this: InvalidOperationException while executing 'performed' callbacks of 'Player/Movement[/Keyboard/w,/Keyboard/a,/Keyboard/s,/Keyboard/d]'

errors input actions

Here is the code

using UnityEngine.InputSystem;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private CustomInput input = null;
    private Vector2 moveVector = Vector2.zero;
    private Rigidbody2D rb = null;
    private float moveSpeed = 10f;

    private void Awake() {
        input = new CustomInput();
        rb = GetComponent<Rigidbody2D>();
    }

    private void OnEnable() {
        input.Enable();
        input.Player.Movement.performed += OnMovementPerformed;
        input.Player.Movement.canceled += OnMovementCancelled;
    }

    private void OnDisable() {
        input.Disable();
        input.Player.Movement.performed -= OnMovementPerformed;
        input.Player.Movement.canceled -= OnMovementCancelled;
    }

    private void FixedUpdate() {
        rb.velocity = moveVector * moveSpeed;
    }

    private void OnMovementPerformed(InputAction.CallbackContext value){
        moveVector = value.ReadValue<Vector2>();
    }

    private void OnMovementCancelled(InputAction.CallbackContext value){
        moveVector = Vector2.zero;
    }
}


How to solve this problem?

I regenerated project files, put in assembly definition Unity.InputSystem

sorry for my bad english


Solution

  • The exception is literally telling that you're trying to read a Vector2 value from a control that has an output value of type float. In order to change the output value type to Vector2 your action should be of a composite type. You can download a sample provided with InputSystem to explore it in detail and understand how to set up controls properly.