NullReferenceExeption

Iam still new to this stuff but i got an error i just cant understand.

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

public class Attack : MonoBehaviour
{
    [SerializeField]
    private int speed;

    [SerializeField]
    private GameObject textObj;

    private TextMeshPro text;
    private int score = 0;

    private void Start()
    {
        text = textObj.GetComponent<TextMeshPro>();
    }

    private void Update()
    {
        transform.Translate(new Vector3(0, -1, 1) * Time.deltaTime * speed);
        if (transform.position.y < -5)
        {
            score++;
            transform.position = new Vector3(Random.Range(-10, 10), 6, 0);
            text.text = "Score: " + score;
        }
    }
}

Everytime the text on the text Object should change, it throws an error with NullReferenceExeption but i attached the text-object in the inspector to textObj.

So you know, you’re expecting someone to know what’s wrong by posting code. Try posting the full error which tells you exactly what part of the code is NULL. It means NOTHING is assigned to that object so you need to investigate why. Showing the code won’t help.

You attached a gameobject to a GameObject variable. But then you’re trying to get a component off of it. So if you are getting a null error, and you go to the line where the null error is being thrown, then you must have a null component. Now solve for null.

Fortunately this one is easy. It doesn’t even matter what you are doing.

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7