Why isn't my movement script working (NullReferenceException)

im new to unity and my movement script keeps giving me this error:

NullReferenceException: Object reference not set to an instance of an object

here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    private float horizontal;
    private float speed = 8f;
    private Rigidbody2D rb;

    void FixedUpdate()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        rb.velocity = new Vector2(horizontal * speed, 0);
    }
}

The problem is that while you created a Rigidbody2D object named “rb”, the object right now is empty and does not point to anything.

so when you call:

rb.velocity = new Vector2(horizontal * speed, 0);

you actually try to change an unkown rigidbody’s velocity.

if you want the “rb” object to point to your player’s rb, you’ll need to add the following lines:

void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

This way, rb will point at the Rigidbody2D of whichever object the script is used in :slight_smile: (in your case, player)