DoNotPutMeInABox
DoNotPutMeInABox

Reputation: 85

Unity Physics2D.IgnoreCollision not functioning properly

I'm attempting to get two objects to ignore each other. I tried to implement the Physics2D.IgnoreCollision code, but as it stands, the first object falls from the sky, and either A) directly hits the object below, stays there for a second, and then continues moving down the screen, or B) merely glances off the object below if it hits it from a side angle. I want the two to completely ignore each other.

Here is my code:

void OnCollisionEnter2D(Collision2D collision) {
    if (collision.gameObject.tag == "obj") {
        Physics2D.IgnoreCollision(collision.gameObject.GetComponent<Collider2D>(), gameObject.GetComponent<Collider2D>());
    }
}

Upvotes: 3

Views: 7453

Answers (1)

Ruzihm
Ruzihm

Reputation: 20270

A (typically) better solution is to use layers to manage collision between categories of items. You would assign obj-tagged objects to a particular layer, and the object in your post to another layer, then go into the Unity Physics Manager to disable collision between those layers. Further direction on that is available in the Unity Docs.

But if you must use tags, there is still a solution.

If you're calling Physics2D.IgnoreCollision inside of a collision event, then you are only ignoring their collision after the collision event has affected the velocity, etc. of the objects. So, basically you're calling it too late.

A better alternative to get the behavior you're looking for is to call it in a method that runs after both objects have been created. The challenge there, is that you need a way to get a reference to the other game object you want to ignore.

One solution is to put the call into the objects in their OnEnable() methods, and then use FindGameObjectsWithTag to find the other objects to ignore:

public class OneObject : MonoBehaviour {

    void OnEnable() {
        GameObject[] otherObjects = GameObject.FindGameObjectsWithTag("obj");

        foreach (GameObject obj in otherObjects) {
            Physics2D.IgnoreCollision(obj.GetComponent<Collider2D>(), GetComponent<Collider2D>()); 
        }

        // rest of OnEnable
    }
   // rest of class ...
}

If you put this in the OnEnable of both both types of objects (with the tag of the other object of course), it should meet your needs.

Upvotes: 7

Related Questions