The question is answered, right answer was accepted
2D Object Pickup - Occasionally adding score twice
Hi all, I'm creating my first 2D platform game and having a blast. Things have been going well. However, I've hit a problem with scoring...
Each time the player collects a gem, score increases by 10, and the UI element is updated. Roughly 80% of the time this happens as desired, but the other 20% of the time the +10 is added twice for the same gem. Each play through the issue occurs on a different gem, so it's not a duplicate placement of gem prefabs. Score is controlled through two simple C# scripts:
Score:
public class Score : MonoBehaviour {
public static int scoreValue;
Text scoreText;
void Start () {
scoreValue = 0;
scoreText = GetComponent<Text>();
}
private void Update()
{
scoreText.text = scoreValue.ToString();
}
}
And on the Gem itself:
public class GemScript : MonoBehaviour {
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag.Equals("Player"))
{
Destroy(gameObject);
Score.scoreValue += 10;
Debug.Log("Collected - score" + Score.scoreValue.ToString());
}
}
The Debug.Log shows in the console that the score is added twice, in the same second. As if the OnCollisionEnter2D method is being called twice for the same collision. I've switched both player and gems between Discrete and Continuous collision detection with no change in behaviour.
Help? Please?
Hi @cspecht
I don't think OnCollisionEnter or any similar method would be called twice, Destroy is run in the end of frame, so the gameobject is gone in next frame AFAI$$anonymous$$.
Despite of this, try doing this;
Add a field in your GemScript: "collected = false",
Then inside your if statement, add "collected = true;".
Then change your if to:
if (collision.gameObject.tag.Equals("Player") && collected == false)
Thanks @eses
Yes, that has worked! Nice. Just an extra double-check to ensure it's not doing the collision detection twice - which it is. . .
Looked a little further and it became obvious: my Player has a box AND a circle collider (I use a circle collider for the feet to smooth ramp movement). Obviously both colliders were sometimes triggering the GemScript.
You're awesome.