I’m working in Unity2D in C#. I have a player character with a box collider 2D and circle collider 2D. I want to use an OnCollisionEnter that only triggers when the collision is with the circle collider, not the box collider.
I’ve done a fair bit of googling but couldn’t find a source that explained how I could go about this (at least, not without making separate child objects for the collider which I’d much prefer not to do).
What I’m looking for would basically be something along the lines of:
private void OnCollisionStay2D(Collision2D collision)
{
if (theColliderThatCollided == theCircleCollider2D)
{
// Do Things
}
}
Having two colliders on the same object is not advised. You should have one collider on your object, and another one attached to a child object.
You could do the following to check which collider triggered the OnCollisionStay2D event:
// Click and hold your mouse over the CircleCollider component and drop it to the `CircleCollider` field in the inspector
public Collider2D CircleCollider ;
// Click and hold your mouse over the BoxCollider component and drop it to the `CircleCollider` field in the inspector.
public Collider2D BoxCollider; // Not necessary in the end if you don't want to check against the box collider
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.collider.GetInstanceID() == CircleCollider.GetInstanceID() )
{
// Do Things
}
}
I am not sure if this answers your question correctly since this function would go inside the other object (Not your player). This other object might call a function inside the player. I may be wrong but it appears that the object itself doesn’t know which of its colliders have collided but the other object keeps a reference to it.
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.collider as CircleCollider2D != null)
{
// Collided with a circle collider
}
if (collision.collider as BoxCollider2D != null)
{
// Collided with a box collider
}
}
From Microsoft C# Reference:
The as operator (as) is like a cast operation. However, if the conversion isn’t possible, as returns null instead of raising an exception
Or you might use the ‘is’ operator. Might be more readable: