- Home /
Score is decrementing twice while passing through a collider.
Hi I have a collider through which player will lose 1 point. I implemented the functionality but the score is decrementing twice.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
FindObjectOfType<Coin>().DecrementScore();
}
}
and this is my Coin class.
public class Coin : MonoBehaviour {
static int score;
// Use this for initialization
void Start () {
score = 0;
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player"))
{
score++;
Destroy(gameObject);
}
}
public int getScore(){
return score;
}
public void setScore(int s){
score = s;
}
public void DecrementScore(){
setScore(score-1);
}
}
what could be the possible issue? Please help!
Put a log into your colliding code and see what causes the second trigger.
Do you have more than one Coin in your scene? Because you're currently storing "score" as a static variable, which is almost never a good idea and will be shared by all instances of the class.
In the vast majority of game designs, "Score" should be a property of the player, not of a coin.
Yes, I have more than one coin. I am randomly spawning them own each platform.
Answer by vtunity · Jun 21, 2017 at 07:20 AM
@varun001 Insert this code in player instead of all coins:
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Coin"))
{
score++;
Destroy(other.gameObject);
}
}
Make coin as trigger collider. whenevre player hit to any coin player script OnCollisionEnter2D() will called and you destroy coin on first trigger so no chance to call twice. note that player have nonstatic rigidbody2d and remaning all coins with Collider with Trigger and static rigidbody..