0
\$\begingroup\$

I am creating a game where there would be two objects instantiated. Each one has a script (to check for collisions), a Rigidbody2D component and a Collider2D of course.

The thing is that I want to call a function whenever the two objects collide each other, but when those two objects collide, the function is called twice (once from object1, and once from object2) but I want it to be called once.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The way I handle this is to check the instance ID, and let the object with the lower ID "own" the collision.

void OnCollisionEnter2D(Collision2D collision) {

    if (collision.gameObject.TryGetComponent(out ThisScript otherscript)) {
        // Two of the same script colliding.

        if (gameObject.GetInstanceId() > collision.gameObject.GetInstanceId())
            return; // I have the higher ID — abort!

        // Put code to call only once in
        // same-script collisions here.
    }
}
\$\endgroup\$

You must log in to answer this question.

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