Hi there.
Im beginer in unity\c#. I tryed a few things to fix my error, but i cant.
I try to do a game, where i generate random balls, and then i collect them with clicking.
Here’s the error:
NullReferenceException: Object reference not set to an instance of an object
balldestroy.SetCountText () (at Assets/script/balldestroy.cs:33)
balldestroy.Start () (at Assets/script/balldestroy.cs:14)
And heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class balldestroy : MonoBehaviour {
static int count;
public Text countText;
// Use this for initialization
void Start () {
count = 0;
SetCountText ();
Destroy (this.gameObject, 10);
}
// Update is called once per frame
void Update () {
}
void OnMouseDown() {
if(Input.GetMouseButton (0))
{
count += 1;
SetCountText ();
Destroy (this.gameObject);
}
}
void SetCountText(){
if (countText.text != null){
countText.text = "Count: " + count.ToString (); \heres the error
}
}
}
Welcome to the forum and community.
Please use code tags when you need to post source code.
The countText variable has probably not been assigned in the inspector, so the error might already occur one line above the one that you’ve identified and commented.
If you’re sure that you’ve assigned the variable, ensure there are no other instances of this script which might cause the exception to occur.
As for your null-check, it makes more sense to use this one
if(countText != null)
// or
if(countText) // the text component is a UnityEngine.Object and thus supports boolean-like syntax
Thank for your answer, and sorry for skiping the code tags.
well for starters you Destroy (this.gameObject, 10); which means this.gameobject which means the ball no longer exist.
and i assume public Text countText; you did put in the gameobject you wish to use for this?
otherwise u need to do as following
private text _countText;
void Start ()
{
_countText = GetComponent<Text> ();
}
oh and second thing dont use static variables unless you really need them. since u can access that varible outside of the script without having to create a New instance . just use private.
I used this tutorial for makeing the counter, but it still not working properly, i dont know what can be the reason.:
I closed the unity and reopened it, now i dont have the NullReferenveException.