Home > Software engineering >  InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityE
InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityE

Time:10-09

So I've been tinkering with the Unity input system (the one you install as a package), trying to create a simple movement script, but immediately ran into a problem. The way I did it was create an action of the Value type, then bound WASD to a 2D Composite and then created a Unity event calling on the "Movement" function inside the player script.

public void Movement (InputAction.CallbackContext context)
{
    Debug.Log("!!!!!!");
    Vector2 moveVal = context.ReadValue<Vector2>();
    playerContainer.transform.Translate(new Vector3(moveVal.X, moveVal.Y, 0) * moveSpeed * Time.deltaTime);
}

Anyway, up to this point it all works fine: the function is called on, and the button presses are registered, but any time I press them, it throws two exceptions. "InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityEngine.InputSystem.Composites.Vector2Composite'" and "InvalidOperationException while executing 'performed' callbacks".

The problem seems to be this line:

Vector2 moveVal = context.ReadValue<Vector2>();

but thing is, every single tutorial and solution out there uses the same piece of code, so it should work fine, I guess? What could be causing the problem on my side?

CodePudding user response:

[Disclaimer, this is not an answer but I needed to include the picture/code]

Everything looks OK so I guess the error is in the Input Actions control. Compared to this example, do you see any differences?

enter image description here

To use the Input Actions above I use code like this:

public class PlayWithCube : MonoBehaviour
{
    NewControls newControls;

    private void Awake()
    {
        newControls = new NewControls();
        newControls.Game.Movement.performed  = Movement_performed;
    }

    private void Movement_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
    {
        var v = obj.ReadValue<Vector2>();
        Debug.Log(v);
    }

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

    private void OnDisable()
    { 
        newControls.Disable();
    }
}
  • Related