I am currently working on a videogame and a problme I'm currently running into is the fact that when I'm testing the game I often get double or triple increases in the score when I catch one Star. Does anyone know why this might be happening? Below you will find the script that handles score increases. Thanks in advance
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StarCollision : MonoBehaviour
{
int Score;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball")) // Change this from an update method that runs every frame to a method that only runs when things change (Score script score display method)
{
Score = ScoreScript.scoreValue;
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
Score = ScoreScript.scoreValue;
if (Score == ScoreScript.scoreValue)
{
Debug.Log("My instance: " + GetInstanceID());
Debug.Log("Other instance: " + other.gameObject.GetInstanceID());
}
}
}
private IEnumerator ChangeColor()
{
ScoreScript.score.color = Color.yellow;
yield return new WaitForSeconds(0.1f);
ScoreScript.score.color = Color.white;
gameObject.SetActive(false);
}
}
The score should only increase by 1 for each star that is catched
One option is to disable collision on the star immediately after a collision with the ball occurs. To use this on a pooled star, you would need to re-enable the collision when the star is enabled again:
Collider2D myCollider;
private void Awake()
{
myCollider = GetComponent<Collider2D>();
}
private void OnEnable()
{
myCollider.enabled = true;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball"))
{
// Disable this collider immediately to prevent redundant scoring, sound cues, etc.
myCollider.enabled = false;
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
}
}
If you decide you need collision on the star while the coroutine is occurring, you can add a field to StarCollision
that ensures that the score will only increase once. For a pooled star, again, you would need to ensure that it is reset in OnEnable
:
private bool alreadyScored = false;
private void OnEnable()
{
alreadyScored = false;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball"))
{
if (!alreadyScored)
{
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
alreadyScored = true;
}
}
}
Ok this doesn't work because it makes the clones of my star game object inactive. (i'm using an object pooler to prevent garbage collection)
Alright thanks man. I tested it a couple of times and it seems to work