- Home /
Receiving error"NullReferenceException: Object reference not set to an instance of an object clicktoDestroy.OnDestroy ()"
When clicking to destroy this game object I get an error that says "NullReferenceException: Object reference not set to an instance of an object clicktoDestroy.OnDestroy ()" Thanks in advance! Also im pooling clones of the game object that get deleted
public class clicktoDestroy : MonoBehaviour
{
public Text moneytext;
private int moneyamount;
static GameObject MoneyPooler;
private void Start()
{
moneyamount = 0;
MoneyPooler = GameObject.Find("MoneyPooler");
}
public void OnMouseDown()
{
Destroy(gameObject);
}
public void OnDestroy()
{
Debug.Log("+Money!");
MoneyPooler.GetComponent<MoneyCounter>().IncreaseMoney();
}
}
And my money Counter which doesn't get destroyed
public class MoneyCounter : MonoBehaviour
{
static GameObject money;
static Text moneytext;
static int score;
public void Start()
{
score = 0;
}
public void IncreaseMoney()
{
moneytext.text = "$" + (score + 1);
}
}
Your "moneytext" variable in your $$anonymous$$oneyCounter script is never assigned to, and thus is always null.
If the object exists in the scene, replace static with public, and assign the Text component in the inspector.
Awesome, that worked! But now my number wont go up past 1 and because i'm pooling the money go. I destroy multiple objects. Do you know how I could keep the number increasing ins$$anonymous$$d of adding one and losing it when I destroy the object?
You need to increase the score variable in the Increase$$anonymous$$oney() function:
public void Increase$$anonymous$$oney()
{
score++;
moneytext.text = "$" + (score);
}
Never$$anonymous$$d I figured it out thanks for your help!
Answer by samvid · Mar 29, 2018 at 01:08 AM
Hi @Nokit,
I think bobisgod234 is correct. You have moneytext
in your MoneyCounter class defined as static
variable. It should be public
in order to change its value and then drag and drop the Text component in the Inspector.
Also, from the looks of it, you have defined score
as static variable as well and then instantiated as 0 so what will probably happen is everytime you will call OnDestroy
in the MoneyCounter
the score
will be 1 and that will make moneytext
always stuck at 1. I may be wrong and this is the feature you want then you can ignore this or else I suggest you make a separate class for Score variable and use the instance of that class in MoneyCounter
.