Question by
DariusdXm · Feb 28 at 11:00 PM ·
variablevalueinfinitecontinuous
Infinite value add
I have a code where you collect a chest and it disappears when pressing "E" when entering the chest's trigger, and I wanted to keep in a variable how many chests you collect. It works good, but after you collect the chest, if you keep pressing "E", the number of chests keeps going up. I need some help to fix this. Here is the code:
public int Chests = 0;
private bool pickUpAllowed;
public GameObject gameObject;
private void Start()
{
pickUpText.gameObject.SetActive(false);
}
// Update is called once per frame
private void Update()
{
if (pickUpAllowed && Input.GetKeyDown(KeyCode.E))
{
PickUp();
}
}
private void OnTriggerEnter(Collider collision)
{
Debug.Log($"Collided with {collision.gameObject.name} tagged {collision.gameObject.tag}", collision.gameObject);
if (collision.gameObject.tag == "Chest")
{
pickUpText.gameObject.SetActive(true);
pickUpAllowed = true;
}
}
private void OnTriggerExit(Collider collision)
{
Debug.Log($"Exited Collided with {collision.gameObject.name} tagged {collision.gameObject.tag}", collision.gameObject);
if (collision.gameObject.tag == "Chest")
{
pickUpText.gameObject.SetActive(false);
pickUpAllowed = false;
}
}
private void PickUp()
{
Destroy(gameObject);
Chests++;
}
}
Comment