I am trying to call a collider, when I have more than one type of the specific collider. I am not sure how to go about distinguishing one collider from another.
An example of the code I am referring to is:
if (other is BoxCollider)
{
//Do stuff
}
Looks for any BoxCollider on an object, but if that same object has two box colliders is there anything that can be done?
Specifying which collider by also having a clause of which game object the collider is of, is not useful in this scenario, as my code is:
if (other is BoxCollider && other.gameObject.CompareTag("Enemy"))
{
//Do stuff
}
I would be grateful if anyone whose come across this problem could provide assistance. Thanks.
You can easily compare if two colliders are the same. (colliderA == colliderB)
So as long as you have a reference to a specific collider, you can test if that is the one causing the collision.
You can have a component on the object with multiple colliders, that in turn references all the colliders on the object.
You see if this component exists, then ask it if the colliding object has some other data you need.
As your game grows, the number of box colliders are going to grow a lot. Always check for what you’re actually interested in, not some other detail - if you’re looking for an enemy, check if what you’ve collided with has the enemy script on it, not for the collider type the enemy has.
Here’s a sample of what I was talking about, interchangeable with the comment on enemy script @Baste just made.
public class ColliderCollection : MonoBehaviour
{
public Collider bottomCollider;
public Collider topCollider;
public bool IsTopCollider(Collider other)
{
return (other == topCollider);
}
}
public class ColliderTest : MonoBehaviour
{
public void OnCollisionEnter(Collision col)
{
ColliderCollection cc = col.gameObject.GetComponent<ColliderCollection>();
if (cc)
{
if (cc.IsTopCollider(col.collider))
{
Debug.Log("Hit Top! :smile:");
}
else
{
Debug.Log("Did not hit top :(");
}
} else {
Debug.Log("Hit something else!");
}
}
}