Ashton Sipes
Ashton Sipes

Reputation: 67

Why am I getting a Null Reference Exception when there is clearly a proper reference? (Unity)

I am new to Unity, and I have a tiny bit of code which I actually took directly from a tutorial for Unity. The tutorial can be found here, at about 12:46
https://www.youtube.com/watch?v=7C7WWxUxPZE

The script is properly attached to the game object, and the game object has a Rigidbody Component.

The tutorial is a couple years old, but I looked things up in the API and everything appears to be the same as far as this particular bit of code is concerned.

Here is the script:

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

public class PlayerController : MonoBehaviour {
private Rigidbody rb;

void Start()
    {
    rb.GetComponent <Rigidbody> ();

    }


void FixedUpdate() 
    {

    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);    

    rb.AddForce (movement);
    }
}

I get NRE at two locations:

rb.GetComponent <Rigidbody> ();

rb.AddForce (movement);

Upvotes: 0

Views: 1210

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

You should not be calling GetComponent on the rb object. You should call GetComponent on the class MonoBehaviour itself. You then need to take the result of that call and assign it to rb

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

If after fixing this you still get the NRE on the rb.AddForce (movement); call that means the game object the script is attached to does not have a Rigidbody attached to it you will need to make sure you add one to the object too.

To go beyond what the tutorial shows, one thing you may want to do is put the RequireComponent attribute on your MonoBehavior class so the script will automaticly add a Rigidbody to the game object if one does not already exist.

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

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {
private Rigidbody rb;

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

    }


    void FixedUpdate() 
    {

        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);    

        rb.AddForce (movement);
    }
}

Upvotes: 2

Related Questions