- Home /
How to prioritize colliders?
Hi, I've got a Object with a rigid body (so that does manage the collision triggers), Sometimes it will collide with 3 different GameObjects at the same time . How can I tell it to forget about the other colliders if one of the 3 got a priority on others?
I'm working with the tags so far, but it seems that the collisions does not care about the order in the code:
private void OnTriggerEnter(Collider other)
{
if (other.transform.parent.tag == "Obstacle")
{
//PRIORITY CODE is not executed in first
}
else if (other.transform.parent.tag == "Enemy")
{
//SECONDARY CODE, but executed first :/
}
}
Answer by MKFusion · Apr 05 at 07:55 PM
Hi I know it's not a perfect solution, but I had a similar issue few days ago.
One way would be to set a private flag variable, "hasColided" for example. Then on Trigger you just check at the beginning if the other collided object has that flag set to true.
HI, thanks for you answer I don't know if I understand well your private flag variable concept.. Are you talking about some private var inside the class? For instance in my project I ve already got this, the object that have got the rigidbody, collides at first with 3 GameObject tagged "enemy", in order to only collect with the first enemy, I've got a bool "hasBeenTriggered" false at start and in the code :
private void OnTriggerEnter(Collider other)
{
if (hasBeenTriggered)
return;
if (other.transform.parent.tag == "Obstacle")
{
hasBeenTriggered = true;
Debug.log("Obstacle Trigger");
}
else if (other.transform.parent.tag == "Enemy")
{
hasBeenTriggered = true;
Debug.log("Enemy Trigger");
}
But in the above example, even if 3 Enemy and One obstacle are at the exact same place, it will only Debug "Enemy Trigger" (once as expected); But I want to prioritize the Obstacle first.. It seems that the enemy tag is triggered first prior to the Obstacle tag.
yes, if there's no enemy that trigger the same collider at the same time. Imagine a 2d plane, where enemies run over it. your mouse cursor is an aim, and when you click it it instantiate a bullet object (the one with the Rigidbody with this code on it) for 0.1sec, if it makes a collision, the bullet object is destroyed. if this bullet intersects with 4 enemies (4 at the same place they overlap), it will collide with one enemy (thanks to the hasbeenTriggered). If the bullet touch an obstacle (which enemies are supposed to take cover behind) it collides with the obstacle as expected.
But when an enemy and a an obstacle are at the same spot, where my code logic would tell the bullet to collide with the obstacle, in this case it collides with the enemy. Somehow the triggers on the enemies are called first.
I've made a workaround for this actually, with the enemies disabling their colliders when they enter an obstacle collider, but this involves an unnecessary collision check.