- Home /
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);
}
}
}
Answer by Shrimpey · Feb 20 at 01:10 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613053250im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I make a button appear when my player enters a trigger? 1 Answer
Click/touch object to enable/disable buttons inside Canvas 1 Answer
Trigger implementation 1 Answer
OnTriggerStay with multiple collision parameters 1 Answer
Light animation and Main Menu animation at same time from 1 trigger 0 Answers