Problem with int values + 1 gives unexpected values
Hi everyone, I'm about to launch my game but I'm facing this crazy weird bug that I failed to see the cause of it so I have diamonds in my game simply everytime the player takes the diamond the number of diamonds he has increases by 1. but for some reason randomly increases by 2 or 3 ! Here is my code: (using unity 2017)
public class Diamond : MonoBehaviour {
private LevelManager theLevelManager;
public GameObject DiamondUI;
// Use this for initialization
void Start () {
theLevelManager = FindObjectOfType<LevelManager>();
DiamondUI.SetActive (false);
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Player") {
theLevelManager.AddDiamond ();
DiamondUI.SetActive (true);
gameObject.SetActive (false);
}
}
}
and this is the part of the code in the level manager script:
public void AddDiamond ()
{
diamondCount += 1;
DiamonText.text = "" + diamondCount;
}
ofcourse at the start of the game I put diamondCount = 0;
Answer by SheikhAlkaf · Dec 02, 2019 at 03:44 PM
found the answer, incase anyone had this problem. the sulition is to add a bool so the trigger wont be called many times than desired.
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Player" && !isCollected) {
isCollected = true;
theLevelManager.AddDiamond ();
DiamondUI.SetActive (true);
gameObject.SetActive (false);
}
}
Your answer
Follow this Question
Related Questions
Way of Finding/accessing a variable from another script though another variable? 1 Answer
How can i get the name of the gameobject that triggered a trigger? 1 Answer
(SOLVED) Need help with Script that is supposed to get components of an AI and change them 1 Answer
How to make an object move to the direction in which the user faces using vr gaze interaction? 1 Answer