- Home /
HOW TO CALLBACK COLLIDER WITH NAME?
hi, sorry for my bad English, I’m trying to make a platform game 2d, the player has two objects. The parent object contains two Colliders2d (box, circle), but I don’t know how to recall the Collider by name on "onCollisionEnter" please help me!! thanks.
Answer by tocu-adrian · Jul 21, 2020 at 02:30 PM
Hi, If i understand, you want the collider name; Try this:
private void OnCollisionEnter2D(Collision2D collision)
{
var collider = collision.GetContact(0).collider;
var otherCollider = collision.GetContact(0).otherCollider;
}
Tell me if you have any problems.
thanks, the code works, but the collision is detected in both Colliders even if the other object touches only one...
Do you want something like this: when an object collide with the box collider then he must execute an action and when it collide with the circle it must execute another action ?
For this you can do something like this :
private void OnCollisionEnter2D(Collision2D collision)
{
var collisionWith = collision.GetContact(0).otherCollider;
if(collisionWith.name == "box")
{
//do box behaviour
}
else if (collisionWith.name == "circle")
{
//do circle behaviour
}
}
Keep in $$anonymous$$d that in "collisionWith.name" is stored the name of the gameobject that contain one of your collider. This is the case where you have two gameobjects as child of your parent, each of them have an collider.
But if you have one parent with two colliders. And you want to detect which collider was hit, then do this:
private void OnCollisionEnter2D(Collision2D collision)
{
var collisionWith = collision.GetContact(0).otherCollider;
if(collisionWith.GetType() == typeof(BoxCollider2D))
{
Debug.Log("Box Collider");
}
else if (collisionWith.GetType() == typeof(CircleCollider2D))
{
Debug.Log("Circle Collider");
}
}
thank you so much for your availability, problem solved!!
Answer by gjf · Jul 21, 2020 at 01:51 PM
You mean OnCollisionEnter()
, right?
https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
hi, I tried this code, but don't work....
if (GetComponent().GetType() == typeof(BoxCollider2D)) { Debug.Log("Box") } if (GetComponent().GetType() == typeof(CircleCollider2D)) { Debug.Log("Circle") }
Your answer
Follow this Question
Related Questions
Weird ContactPoint2D on two BoxCollider2D collision 0 Answers
Workarounds for Higher Control When Using Physics2D? 0 Answers
OnTriggerExit2D not working on android (but works in editor) 0 Answers
Player not taking damage on collision with enemy 1 Answer
(Beginner) Adding a 2D Collider Randomly moves Player Off-screen when Game Starts!! 1 Answer