- Home /
NullRefrenceException with new input system
Hi, so I have a movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
public Controls controls;
public CharacterController2D controller;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
public Collider2D player;
[Range(1f, 150f)]
public float runSpeed = 40f;
Vector2 move;
void Awake()
{
controls = new Controls();
controls.Player.Jump.performed += ctx => Jump();
controls.Player.Move.performed += ctx => move = ctx.ReadValue<Vector2>();
controls.Player.Move.canceled += ctx => move = Vector2.zero;
}
void Update()
{
horizontalMove = move.x * runSpeed;
Time.timeScale = Mathf.Clamp(Time.timeScale, 0f, 1f);
Keyboard kb = InputSystem.GetDevice<Keyboard>();
Gamepad gp = InputSystem.GetDevice<Gamepad>();
if (kb.shiftKey.isPressed || gp.rightTrigger.isPressed)
{
crouch = true;
}
else
{
crouch = false;
}
}
void FixedUpdate() => MovePlayer();
void Jump() => jump = true;
void MovePlayer()
{
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
void OnEnable() => controls.Player.Enable();
void OnDisable() => controls.Player.Disable();
}
I don't see anything wrong with it, but unity comes up with this error:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:42)
Does anyone know how to fix this?
Without the code for the CharacterController2D, I wasn't able to test your code myself. However, I think you may want to consider using an InputAction rather than using Keyboard and Gamepad. Originally you had:
if (kb.shiftKey.isPressed || gp.rightTrigger.isPressed)
{
crouch = true;
}
else
{
crouch = false;
}
Which would become something like
crouch = controls.Player.Crouch.ReadValue<float>() != 0f;
However, a better approach would be to use .started and .canceled, similar to how you used .performed for the $$anonymous$$ove action.
void Awake()
{
controls = new Controls();
controls.Player.Jump.performed += ctx => Jump();
controls.Player.Crouch.started += ctx => crouch = true;
controls.Player.Crouch.canceled += ctx => crouch = false;
controls.Player.$$anonymous$$ove.performed += ctx => move = ctx.ReadValue<Vector2>();
controls.Player.$$anonymous$$ove.canceled += ctx => move = Vector2.zero;
}
One thing to add, is the above approach requires the InputAction to use a Press and Release interaction to work correctly.
Your answer
Follow this Question
Related Questions
How can I stop the player movement from being too fast while moving diagonally in my 2D game? 2 Answers
Making a bubble level (not a game but work tool) 1 Answer
Enemy not moving towards Player 0 Answers
2D-Enemy AI problem (2problems) 2 Answers
,Look rotation viewing vector is zero and character always facing 1 direction when idle 0 Answers