Reputation: 35
So I have been learning Unity recently and I have a problem. I'm making a top down shooter and when my tank shoots the enemy I want a score displayed in the top. But I also have a Destroy function to destroy my enemy when a bullet hits them, and it is also destroying the scoreText.
The code in my CollisionWithEnemy class
public class CollisionWithEnemy : MonoBehaviour
{
public static double score = 0;
public Text scoreText;
void OnCollisionEnter2D(Collision2D collision)
{
Score();
Destroy(gameObject);
}
public void Score()
{
score += 0.5;
if (score % 1 == 0)
{
Debug.Log(score);
scoreText.text = score.ToString();
}
}
The error I get in Unity: Object reference not set to an instance of an object.
My question is how can I get the score to keep displaying even after a game object has been destroyed?
Upvotes: 2
Views: 191
Reputation: 998
If you are getting Object reference not set to an instance of an object.
then the problem is likely scoreText
did not get set. Ensure you have set this via the inspector.
Is scoreText
childed to an object that gets destroyed? If so remove it as a child.
Do all objects that have this script have scoreText
set? If not you will receive errors.
Upvotes: 0