So I am trying to create a new first-person movement system with the new input system in order to make gamepad support so much easier and I am experiencing a problem when I try to read the value of the Vector2 in a FixedUpdate
loop, it only outputs (0,0)
but if I read it in an InputAction.performed
event it works. However, I cannot use the event as it doesn't repeat on keyboard input and it isn't smooth. I've seen a tutorial linked here and at the end it does demonstrate you can pull information from outside events. Now my question is did I miss something or is there a different way to do it, my code is found below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Assertions;
public class MovementEngine : MonoBehaviour
{
public InputMaster Input; // My input device here
public float currentSpeed = 2f;
public float walkingSpeed = 2f;
public float runningSpeed = 4f;
public Transform cameraTransform;
public CharacterController controller;
public InputAction Movement;
// Start is called before the first frame update
void Awake()
{
Input = new InputMaster(); // Creates new instance
}
void OnEnable()
{
Movement = Input.Player.Movement;
Movement.Enable(); // it is enabled
Input.Player.Interaction.performed = Interact;
Input.Player.Interaction.Enable();
}
private void Interact(InputAction.CallbackContext context)
{
Debug.Log("Interact");
}
void OnDisable()
{
Movement.Disable();
Input.Player.Interaction.Disable();
}
// Update is called once per frame
void FixedUpdate(){
Debug.Log("Movement: " Input.Player.Movement.ReadValue<Vector2>()); // doesn't work
}
}
CodePudding user response:
Store the value (retrieved in the performed event) in a variable, and use that variable in fixed update.
Make sure to reset the variable from the cancelled event (otherwise the variable will hold the last retrieved value from performed event).
You can read the input value directly into a class variable, as shown below.
// Value read from user input
//
private Vector2 movement;
private void Start()
{
SubscribeEvents();
}
private void SubscribeEvents()
{
// Read the value directly into our movement variable
//
Input.Player.Movement.performed = ctx => movement = ctx.ReadValue<Vector2>();
// Reset the movement variable in cancelled since we are no longer interacting
//
Input.Player.Movement.cancelled = ctx => movement = Vector2.zero;
}
private void FixedUpdate()
{
Debug.Log("Movement: " movement);
}
CodePudding user response:
I fixed this a while ago but StackOverflow never posted my answer
I fixed it by downgrading to Unity InputSystem v1.0.0 as v1.1.1 seemed to not like the InputAction.ReadValue<>()
function.