NullReferenceException Object reference not set to an instance of an object useng 1D axis

NullReferenceException: Object reference not set to an instance of an object
TestingInputSystem.Update () (at Assets/TestingInputSystem.cs:26)

using UnityEngine;
using UnityEngine.InputSystem;

public class TestingInputSystem : MonoBehaviour
{
    private PlayerInput playerInput;
    private Rigidbody2D rigidbody2DThis;
    private PlayerInputActions playerInputActions;
    private void Awake()
    {
        rigidbody2DThis = GetComponent<Rigidbody2D>();
        playerInput = GetComponent<PlayerInput>();

        PlayerInputActions playerInputActions = new PlayerInputActions();
        playerInputActions.Enable();
        playerInputActions.Gameplay.Moving.performed += Moving;
    }
    private void Update()
    {
        float input = playerInputActions.Gameplay.Moving.ReadValue<float>();
        float speed = 55f;
        rigidbody2DThis.AddForce(new Vector2(input, 0) * speed, ForceMode2D.Force);
    }
    private void Moving(InputAction.CallbackContext context)
    {
        Debug.Log($"Moving context = {context.ReadValue<float>()}");
        float input = context.ReadValue<float>();
        float speed = 55f;
        rigidbody2DThis.AddForce(new Vector2(input, 0) * speed, ForceMode2D.Force);
    }
}

Line 25 is an opening bracket in the code you’ve posted, so you haven’t copied the code in as it shows in your file, so it’s very hard to actually work out where your null ref is.

Nonetheless, every null-ref is the same. Work out what’s null, work out why it is null, then stop it being null.

20 edited

Hire

float input = playerInputActions.Gameplay.Moving.ReadValue<float>();

I now.

This is not null.
This line returns this variable

Debug.Log($"Moving context = {context.ReadValue<float>()}");

Either the playerInputActions or the Gameplay or the Moving is null. Before that line add a Debug.log for each one to see what is happening.

Thanks!

This is mistake

    {
        rigidbody2DThis = GetComponent<Rigidbody2D>();
        playerInput = GetComponent<PlayerInput>();

        //PlayerInputActions playerInputActions = new PlayerInputActions(); mistake
playerInputActions = new PlayerInputActions();
        playerInputActions.Enable();
        playerInputActions.Gameplay.Moving.performed += Moving;
    }