Add value to counter.

Hello guys I have a problem: I created a script that when I destroy an object (image / goldcoin), I add a value to a counter UI. Since I have several gold coins (categories) in the game, in the same script I would like to create more than one object (gold coin) during which, for each gold coin, I add a value so as not to create the same script for each gold coin. Could you help me understand how to proceed? Thanks so much.

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

public class increasemonete : MonoBehaviour
{

    public Text ScoreText;
    public int counter;
    public GameObject[] GoldCoin;
  

    void Start()
    {
        counter = 0;
     
    }

    void Update()
    {
        if (GoldCoin == null)
        {

            counter = counter =+ 1;
        }
        ScoreText.text = counter.ToString();
    }
}

One approach is to make a central manager that controls single-item stuff like the player’s score, perhaps the actual display of that score, etc. This pattern is sometimes called a singleton pattern, or GameManager pattern.

Then the gold collection script would contact that manager to inform the tally system that you got coins. In turn that system would update the display.

There’s lots of Youtube tutorials on this concept, as it is widely used.

If you wanna go for it yourself, here are some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

Unity3D Singleton with Prefab used for predefined data:

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}