2
\$\begingroup\$

I have a bullet script that trigger on collision with an enemy, problem is when two enemies colliders overlaps and trigger with bullet both disapear instead of one only. Is there any way to only trigger one?

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.GetComponent<Enemy>())
    {
        collision.GetComponent<Enemy>().DisableUnit();
        gameObject.SetActive(false);
    }
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The docs note that: Trigger events are sent to disabled MonoBehaviors

So SetActive(false) probably isn't enough. Try a hitEnemy flag and only do something when it's false:

private bool hitEnemy = false;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.GetComponent<Enemy>() && !hitEnemy)
    {
        hitEnemy = true;
        collision.GetComponent<Enemy>().DisableUnit();
        gameObject.SetActive(false);
    }
}

or simiply delete the bullet gameobject:

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.GetComponent<Enemy>())
    {
        collision.GetComponent<Enemy>().DisableUnit();
        Destroy(gameObject);
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .