Reputation: 1217
I have an Enemy with two different Collider. The first is a Box Collider, it's used as the enemy hitbox.
The second is a Sphere Collider which I want to use to detect the player and his allies. This collider have the property IsTrigger set to true (the BoxCollider don't).
My problem is that, when my player launch a projectile, it hits the Sphere Collider first. The Sphere Collider is treated as a hitbox and my Enemy takes damages. Here is the projectile script:
void OnTriggerEnter (Collider col)
{
if (col.gameObject.tag == "Player")
{
AUnit a = col.gameObject.GetComponent<AUnit>();
if (a != null)
{
a.takeDamage(damage);
if (goThrough == false)
Destroy(gameObject);
}
}
}
My question is quite simple, how can I do to detect only detect the BoxCollider and ignore the SphereCollider ?
Upvotes: 2
Views: 6450
Reputation: 221
If you don't want them to work layer based since in some situations this won't completely work without a large workaround you can use the following solution which should also work well.
public class "ClassNameHere": MonoBehaviour
{
public BoxCollider2D Collider1;
public CircleCollider2D Collider2;
public CircleCollider2D Collider3;
private void OnCollisionEnter2D(Collision2D other)
{
if(other.collider==Collider1)
{
Debug.Log("1");
}
if(other.collider==Collider2)
{
Debug.Log("2");
}
if(other.collider==Collider3)
{
Debug.Log("3")
}
}
}
Using this you will do a certain action when collided with a specific collider, even if they are on the same game object.
However note that Collider does not have a id variable or something like that, that allows unity to detect the difference between the same type collider on the same game object. But as long as the colliders are of a different type it will work.
If you want 2 of the same type of collider on a single object but still want to notice the difference you will most likely have to go to unity's class definition for that type collider and add a public int, float, long, or string ID which you can get in code to get which collider of a specific type you interact with.
Upvotes: 2
Reputation: 20033
This can be achieved by using Layer-Based Collision Detection.
You set the player to one layer, and the player projectile to another layer.
You can then make the two layers ignore each other in the collision detection.
Upvotes: 4