Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs

Have a problem with incrementing score

A topic by AgentXMan created 5 days ago Views: 51 Replies: 3
Viewing posts 1 to 4

Hi 

so this is my script 

using UnityEngine;
using UnityEngine.UI;

public class DetectCollisionAndUpdateUI : MonoBehaviour
{

   public int score;

    public Text scoretext;

    private void OnTriggerEnter(Collider other)
    {
        Destroy(other.gameObject);
        AddScore();
    }

    void AddScore()
    {
        score += 1;
        scoretext.text = score.ToString();
    }

}

What i basically want is that i need a script which can detect triggers and then increment the score by one if the trigger is triggered

but for some reason it is sometimes incrementing the score by 2 or sometimes by 3 or any other number

Is there any solution if there is please help! also i want it to appear on a ui text thats why i am referencing it too.

PLEASE HELP!

(1 edit) (+1)

It’s been a while since I worked with Unity, but if I’m not wrong, when you call the Destroy() function on an object, this happens asynchronously. As in, it could happen on this frame, or the next one, or in 10 frames, which is why the score is incremented multiple times.

I would suggest to disable the collider on that object, before destroying it, so it will stop triggering collision callbacks until it’s destroyed.

I can’t remember the exact syntax, but inside “OnTriggerEnter” it should be something like that:

other.enabled = false;

This will ensure that object is not triggering more collision events on the same frame, while Unity will destroy it as soon as possible.

OK THANKS A LOT FOR HELPING

I WILL TRY THE THING YOU TOLD ME

:D

If  the problem is that you have two colliding objects each incrementing the score in their collision callback when you only want one of them to, you need a way to decide which of them is going to do it. I have that issue in my bowling games when a pin is colliding with another pin and I want only one of them to play the pin collision sound. In that case, I check the gameobject unique IDs and decide that the lower number gets to play the sound. Sample code here.

Moderator moved this topic to General Development