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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With