Hey there and welcome to the forum,
in general questions regarding NullRefExceptions are not allowed as by the FAQ. Please remember this for next time. A nullRef is the most easy to solve exception as it always occurs when you want to access a variable which has the value null
.
In your example the variable ballon
can be null as it is an Object/Reference-Type (contrary to value types like numbers which can never be null) So why is it null? Because Unity did not find any ballons. in that moment it just returns null.
balloon = GameObject.FindGameObjectsWithTag("balloon"); //when there are no Objects with the tag `balloon` then this returns null;
if(balloon == null) //check if balloon actually has a value
{
Debug.Log("oh no - no balloons where found");
}
else {
balloonsLeft.text = balloon.Length.ToString();
if (balloon.Length == 0)
{
Debug.Log("All balloons popped!");
}
}
as to why the tag search does not work i cannot tell as this is something that needs more info.
Apart from that - have some hints on how to do this more cleanly:
Your Balloons should have their own script:
//this should be on your Balloon object prefab:
public class Balloon : MonoBehaviour {
public void Start() {
BalloonsRemaining.AddBalloon();
}
//this is called when you use gameObject.SetActive(false);
//use this method if you disable the balloon when it is popped
/*public void OnDisable() {
BalloonsRemaining.RemoveBalloon();
}*/
//this is called when you use Destroy(gameObject);
//use this method if you actually destroy the balloon object when it is popped
/*public void OnDestroy() {
BalloonsRemaining.RemoveBalloon();
}*/
}
Then you want to change your BalloonsRemaining Script in this way:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class BalloonsRemaining : MonoBehaviour
{
public TMP_Text balloonsLeft;
private static int balloonCounter = 0;
void Update()
{
balloonsLeft.text = balloonCounter .ToString();
if (balloonCounter == 0)
{
Debug.Log("All balloons popped!");
}
}
public static void AddBalloon() {
balloonCounter++;
}
public static void RemoveBalloon() {
balloonCounter--;
}
}
I know that you might not be familiar with static
yet but lets try to explain this:
So the idea here is that the balloon itself now has the responsibility to let the counter know when it was created or destroyed/disabled. By using the static
keyword we also don’t have to teach the balloon to find the exact instance of the balloonRemaining script. Instead with static we use a method/variable that now belongs to the class itself instead of one instance of a class.
Then the only thing that the instance of the ballooncounter has to do is to show the number.
Hope this helps, let me know if you have any questions regarding this.