0

I'm creating a 3D endless runner in unity, and I have created an UI that displays the number of coins collected, but if I try to run the script I get this error : NullReferenceException: Object reference not set to an instance of an object CollectableControl.Update () (at Assets/Scripts/Collectables/CollectableControl.cs:18)

This is the script:

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

public class CollectableControl : MonoBehaviour
{
    public static int coinCount;
    public GameObject coinCountDisplay;

    /*void Start()
    {
        coinCountDisplay = GameObject.Find("CoinCount");
    }*/

    void Update()
    {
        coinCountDisplay.GetComponent<Text>().text = "" + coinCount;
    }

I also placed the GameObject that needs to be accessed by the script where it should be

I tried to assign the coinCountDisplay field to the GameObject with the name "CoinCount" in void Start() but that didn't solve the issue, neither restarting the Unity Editor, deleting and recreating the script and adding the GameObject like in the attached picture.

Vixen221
  • 1
  • 1
  • You declare the `coinCountDisplay` variable but you don't initialize it. Then in the `Update` function, you access the uninitialized variable. You probably need a constructor for the `CollectableControl` class in which you initialize the `counCountDisplay`. – Tim Jarosz Dec 28 '22 at 20:51
  • Instead of creating a reference to the GameObject, simply create a reference to the "Text" component and assign it through the editor and use it like this: coinCountDisplay.text = "" + coinCount; Keep in mind using the "GetComponent<>()" method inside your Update() will have a huge impact in the performance of the game. – Pavlos Mavris Dec 29 '22 at 07:15

0 Answers0