I'm getting these error messages when I try to use Unity's new Input System package:
Cannot read value of type 'Vector2' from control '/Keyboard/w' bound to action 'CharacterControls/Movement[/Keyboard/w,/Keyboard/a,Keyboard/s,/Keyboard/d]' (control is a 'KeyControl'
InvalidOperationException while executing 'performed' callbacks of 'CharacterControls/Movement[/Keyboard/w,/Keyboard/a,Keyboard/s,/Keyboard/d]'
Here is the code I'm using:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private CharacterController _charactercontroller;
[SerializeField] private Vector3 _walkDirection;
[SerializeField] private Vector3 _velocity;
[SerializeField] private float _speed;
Animator animator;
int isWalkingHash;
int isRunningHash;
PlayerInput input;
Vector2 currentMovement;
bool movementPressed;
bool runPressed;
void Awake()
{
input = new PlayerInput();
input.CharacterControls.Movement.performed += ctx =>
{
currentMovement = ctx.ReadValue<Vector2>();
movementPressed = currentMovement.x != 0 || currentMovement.y != 0;
};
input.CharacterControls.Run.performed += ctx => runPressed = ctx.ReadValueAsButton();
}
void Start()
{
animator = GetComponent<Animator>();
_charactercontroller = GetComponent<CharacterController>();
isWalkingHash = Animator.StringToHash("isWalking");
isRunningHash = Animator.StringToHash("isRunning");
}
void Update()
{
handleMovement();
}
void handleMovement()
{
bool isRunning = animator.GetBool(isRunningHash);
bool isWalking = animator.GetBool(isWalkingHash);
if ( movementPressed && isWalking) {
animator.SetBool(isWalkingHash, true);
}
if (!movementPressed && !isWalking)
{
animator.SetBool(isWalkingHash, false);
}
if((movementPressed && runPressed) && isRunning)
{
animator.SetBool(isRunningHash, true);
}
if((movementPressed || !runPressed) && isRunning)
{
animator.SetBool(isRunningHash, false);
}
}
private void OnEnable()
{
input.CharacterControls.Enable();
}
private void OnDisable()
{
input.CharacterControls.Disable();
}
}