In Unity (C#), Why am I Getting a Nullreferenceexception and How to Fix It

In Unity (C#), why am I getting a NullReferenceException and how do I fix it?


Explanation

In C# generally, this is caused by referencing a field that hasn't been initialized. For example, if you have a field public List<GameObject> items and you later call items.Add(foo) without first doing items = new List<GameObject>(), then you are trying to add an item to a list that doesn't exist.

However, in Unity specifically, this is most frequently caused by forgetting to set a reference in the inspector. When you create a new component and add a field public Transform destination, then you most likely are intending to assign a prefab in the inspector. If you forget, you're trying to reference something that doesn't exist.

Solutions

If you double-click on the error message in the console window, Unity will (with a few exceptions) highlight the GameObject in the hierarchy that threw the error, and open your code editor and highlight the line of the script where the error occurred.


  1. If you are using any of the Find-like methods to get the GameObject, be sure that the GameObject is active, otherwise Find-like methods will return null or may return the wrong GameObject. If you need the GameObject to be inactive when it is found, you need to use a different way of getting a reference to the GameObject than using a Find-like method to find the GameObject directly, such as having the component register with a Manager-type class.

  2. Looking at the GameObject, make sure you've assigned everything in the inspector that should be assigned.

  3. If everything has been assigned, run the game with the GameObject that threw the error selected. It's possible that you have something in Awake() or Start() that's negating the reference, and you'll see the inspector switch to None.

Image of two Unity inspector fields with nothing assigned


  1. Pay attention to the return types of methods you use to modify objects. For example, if you call GetComponent() or anything similar on an object and the component is not found, it will not throw an error. It will just return null. This can easily be handled with a line like:

    if(thing == null) //log an error, or do something to fix the reference else //do what you wanted to do

That should cover the most frequent Unity-specific causes. If that still isn't fixing your issue, Unity's own page on NullReferenceException, and for C# generally, there's a more in-depth explanation of NullReferenceException in this answer.

I have a problem with NullReferenceException in Unity. Can someone help me

the Start method name first letter must be capital

private void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
}

I am getting a NullReferenceException with unity collisions

This is because you are using GetComponent in a class that does not have it and should find GameMechanics in it, but the result is null.

GetComponent<GameMechanics>().playerScore++; // GameMechanics dosen't found..


One way is to give GameMechanic to the other object's is through the inspector:

public GameMechanics Mechanics;
private void OnCollisionEnter2D(Collision2D collisionInfo)
{
if (collisionInfo.collider.name == "Player") Mechanics.playerScore++;
}

However There are other ways to reference GameMechanic and Manager classes in other objects, the best of which is Singleton. here is a simple way to solve your problem easy and that is to use FindObjectOfType. Change the code below and it will probably be fixed.

if (collisionInfo.collider.name == "Player")
{
FindObjectOfType<GameMechanics>().playerScore++; // replace it with this way
}

Inventorysystem in unity getting Nullreference error

Did you initialize the inventoryslots variable?
You need to this, like you did with the item variable in Items item = new Items();.

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

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);
}
}


Related Topics



Leave a reply



Submit