Saturday, July 8, 2017

OnTriggerEnter Re-entrance

This is more of a lessons-learned while developing a game, and I'm creating a post as a reminder for myself.  In this scenario I was using the OnTriggerEnter function to determine when the object would be destroyed.

The issue I was running into was that in some rare cases, multiple objects would trigger this function simultaneously, causing this function to call multiple times before the object was actually destroyed.

Adding a class flag solved my issue, in my case I called it isDead:

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Bullet" && !isDead)
        {
            Destroy(this.gameObject);

            system.UpdateBugCount(-1);
            isDead = true;
        }
    }

The flag prevents re-executing the function after the object should technically be destroyed.

No comments:

Post a Comment