Home > Back-end >  (unity) How to know which collider triggered an OnTriggerEnter call?
(unity) How to know which collider triggered an OnTriggerEnter call?

Time:12-20

I'm trying to detect which collider of one 2d game object got triggered. Obviously using box collider 2d, I've tried to use this method, but even thought the collision in which the game object has an inbuilt script to destroy itself on collision, that works perfectly, thing is this one, for some reason doesnt work (doesnt print anything):

void OnTriggerEnter2D(Collider2D col)
{
    if (col.IsTouching(playerCol))
    {
        print("player collider hit");
    }
...
...
}

The player collider is set as it should be: https://prnt.sc/23oe10m

EDIT: It actually triggers with another collider, just not with the one i want to which seems to work perfectly fine.

Note: If i dont use isTouching, the collider works perfectly as i want to, thing is i need to use the method isTouching to check which collider it hits then run the code that want to get executed as i want to exclusively get stuff triggered from playerCol. Also the OnTriggerEnter2d in the script that is inside the col.gameObject works perfectly as it deletes the gameObject on collision with the playerCol (what i want to do), but the isTouching method isnt working for this.

EDIT2: I've got a literally exact copy of this gameObject im having trouble with, and it does actually print something, while this other gameObject that im having issues with doesnt.

Any ideas?

CodePudding user response:

So I've found out that it might be a bug of my current version of Unity (2019.2.17f1) that Collider2D.isTouching() method doesnt really work properly with Polygon Colliders, because I've casted it here:

void OnTriggerEnter2D(Collider2D col)
{

    if (col.IsTouching(playerCol) == true)
    {
        print("playerHit");
    }
    if (col.gameObject.CompareTag("Bullet") && col.gameObject.layer != gameObject.layer && !col.IsTouching(laserCol)) 
    {
        int hit;
        hit = col.gameObject.GetComponent<BulletScript>().damage;
        Attacked(hit);
        print("Player has taken "   hit);
    }
...
}

And surprisingly the upper if statement doesnt work, the only difference being the Polygon collider, and the one below does.

Conclusion: I switched to detect if the collider overlapping col in the IsTouching method call isnt equal to the secondary collider of the player, instead of detecting if the collider overlapping col is equal to playerCol, and it solved the issue.

It must be that Polygon Collider 2D is bugged for that version.

CodePudding user response:

You may print the name of the GameObject attached to col.

  • Related