How to call OnTriggerEnter once

I’m creating some sort of score system. There’s a GUI Text which will show you your score. Every time you hit a triggered, invisible object, your score will raise by one. However, if I use the function “OnTriggerEnter” it gets called at least 14 times. It gets called in the time you are IN the object. I believe OnTriggerStay should function like that.

Anyway, here is my code:

public static int pScore = 0;
    public GUIText ScoreText;

    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject)
        {
            pScore++;
            ScoreText.text = "" + pScore;
            print("Test");
        }
    }

Thanks

Most likely you should be more precise while checking what cause collision.

In

if (collider.gameObject)

check also for something unique for you main object, as name or tag.

What if you tried,

public static int pScore = 0;
public GUIText ScoreText;

void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.gameObject)
    {
        pScore++;
        gameObject.collider2D.enabled = false; 
        ScoreText.text = "" + pScore;
        print("Test");
        gameObject.collider2D.enabled = true;
    }
}

This may work but might not, sorry if it doesnt work.
I had a simliar problem where my player would “jump” and “doublejump” at the same time.

I hope it works for you.

FYI OnTriggerEnter is called only once by default, when ever some thing enter the trigger. So you don’t have to worry about calling it only once. Only OnTriggerStay is called repetitively untill the object leaves the trigger.

use collision instead of collider

You can do it like this use bool to check whether it has finished or not if it helps give it alike

[SerializeField] int ammoCount = 5;
[SerializeField] AmmoType ammoType;
bool picked = false;
private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Player" && !picked) // I'm using bool to check whether it has trigger 
    {
        print("Gained Ammo");
        FindObjectOfType<Ammo>().IncreaseAmmo(ammoType, ammoCount);
        picked = true;
        Destroy(gameObject);
    }
}

`