Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with int values + 1 gives unexpected values

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;

like image 926
Strong Jaguar Avatar asked Dec 13 '25 04:12

Strong Jaguar


2 Answers

Update runs dozens of times per second. This means the collision function can run multiple times before the diamond is actually deleted. The easiest thing to do would be to give the diamond class a property isCollected. Set it to true the first time you collide, and ignore collisions if its already true.

void OnTriggerEnter2D (Collider2D other)
{
    if (other.tag == "Player" && !isCollected) {
        isCollected = true;
        theLevelManager.AddDiamond ();
        DiamondUI.SetActive (true);
        gameObject.SetActive (false);
    }
}

You can just say that the player gets extra diamonds if they're lucky.

Otherwise, this article might be of help.

TLDR: some colliders do fire multiple times. They recommend that you set a flag, say isColliding, in OnTriggerEnter2D and clear it in Update.

like image 28
IMil Avatar answered Dec 15 '25 17:12

IMil