Why does the money counter resets when I pull different objects trough the trigger?


I need help! I’m making a game where you earn money if you pull an object (with the tag “Valuable”) trough a trigger. The problem is that it starts counting from 0 every time the trigger is triggered by a different object. If you pull the same object trough the trigger several times, the counting works, but I want it to destroy the object so you can’t pull it trough the trigger several times.


Here is the code which is assigned to the object I want to sell:

using UnityEngine;
using TMPro;

public class Valuable : MonoBehaviour

{
    public TextMeshProUGUI countText;
    private int count;

    // Count = Money
    void Start()
    {
        count = 0;
    }

    void SetCountText()
    {
        countText.text = "Money: $" + count.ToString();
    }


// When something goes trough the trigger, it will add money and destroy the object
private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.CompareTag("SellObject"))
        {
            other.gameObject.SetActive(true);
            count = count + 500;

            SetCountText();
            Destroy(gameObject);
        }
    }
}

Your count integer is not static, so it is tied to the gameobjects that you’re destroying.
Change

private int count;

to

public static int count;

And if you’re instantiating objects, they will perform Start() and reset it everytime as well. Not sure how you’re spawning them, so keep that in mind.