Object Reference Not Set to an Instance of an Object

I have just started creating a new game in Unity and I have immediately ran into a problem. I made a simple 1 x 1 cube and I attached this script to it…

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

public class PlayerUnit : MonoBehaviour
{
    Rigidbody rb;
    public float speed = 5f;
    // Start is called before the first frame update
    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
     rb.position += Input.GetAxis("Vertical") * transform.forward * Time.deltaTime * speed;
     rb.position += Input.GetAxis("Horizontal") * transform.right * Time.deltaTime * speed;
    }
}

As you can see, it is a very simple piece of code that should make the controls w, a, s, and d move my character, however instead of my character moving it just gives me this error…
NullReferenceException: Object reference not set to an instance of an object
PlayerUnit.Update () (at Assets/Scripts/PlayerUnit.cs:18)
If anyone can help me please do…

Nothing there is setting the reference “rb” to an instance of a Rigidbody. You could set rb to public and set it using the Inspector, or add this to the Start method (assuming you have a Rigidbody component on this GameObject, and this script is attached to the GameObject you wish to control).

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

See if that clears up the issue.

Wow, I can’t believe I missed that lol… thank you so much for helping me fix the problem!

1 Like