Null Reference exception (735134)

I have a problem with my code . I was working on displaying it if certain condition is met for counting by destroying objects but I keep getting an error, but my game works even with the error but I have to press the || button. I have no idea of what I did wrong. I would love to remove the error.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DestroyScript : MonoBehaviour
{
    public Text countText;
    private int count;
    public Text winText;
    void Start()
    {
        count = 0;
        SetCountText ();
        winText.text = "";
    }
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Pick Up"))
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText();
        }
    }
    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
        if(count >= 12)
        {
            winText.text = "You Can buy Pizza now!!!";
        }
    }
}

My error is :
NullReferenceException: Object reference not set to an instance of an object
DestroyScript.SetCountText () (at Assets/DestroyScript.cs:32)
DestroyScript.Start () (at Assets/DestroyScript.cs:16).

Any help would be greatful thank you

Since countText and winText are public, objects that have this script will show those public variables in the inspector. Those fields will start empty/null. Doing it this way, you’ll need to drag references to them from the respective UI elements, for each object that has this DestroyScript.

This can quickly become a pain in the butt. A more automatic way to handle this is in your Start() function, get a reference to the UI element as follows:

void Start()
{
     countText = GameObject.FindWithTag("CountText").GetComponent<Text>();
     winText = GameObject.FindWithTag("WinText").GetComponent<Text>();

     count = 0;
     SetCountText ();
     winText.text = "";
}

Then, just once, you’ll need to add the “CountText” and “WinText” tags to their respective UI elements.

Doing it this way, you should probably make countText and winText private so at the very least you don’t clutter the inspector.

1 Like