Add points on destroy

I had a code for a coin that destroyed it when i collided with it and wanted to add a score counter but for some reason it says that i havent referenced the object to an instance (on the score.text line).

This is the code:

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

public class Destroy : MonoBehaviour
{
    public Text score;
    int points = 0;

    private void OnCollisionEnter2D(Collision2D other) {
        points ++;
        score.text = points.ToString();
        Destroy(gameObject);
    }
}

Your problem is that the score variable is part of this game object that you are destroying. It’s what we call an instance variable. When you create the coin, the score variable is created. However, when you destroy it, it, too, is destroyed and disappears.

If you make the score static, it becomes a class variable and exists as long as the class does. Another problem is that you will have lots of coins and you’ll have to copy the Score text field into every one of them. You are creating dependencies.

You can avoid having to copy the text game object across by having the coin script search for it.

Another thing is that we tend to use triggers to collect coins. A collision may do a bunch of calculations to do with transfer of momentum and so on. In this case, mark the collider on your coin as a Trigger and then use the following code. Physics ignores what you do and you can sleep easily, knowing you’ve saved a few calculations :o)

using UnityEngine;
using UnityEngine.UI;

public class Coin : MonoBehaviour
{
    static int points = 0;
    Text score;

    private void Start()
    {
        score = GameObject.Find("Text").GetComponent<Text>();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        points++;
        score.text = points.ToString();
        Destroy(gameObject);
    }
}