0
\$\begingroup\$

I'm a beginner with Unity and I'm developing my very first 2D game. My game character needs to have an automatic right/left movement but I'm struggling with the colliders on the walls (I made a tilemap object and set a collision for each wall on it). I need my character to detect the collision on the Right wall and turn to the left but I just can't find a way to name (I don't even know if you can do this) and detect a specific collider/collision so I can make an if statement on the player script.

How can I detect a specific collision/collider and refer this on my player script?

Here is the code I'm using for it (it isn't working):

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.collider.gameObject.name == "Right Facing Wall")
    {
        runForwards = false;
    }
    else if (collision.collider.gameObject.name == "Left Facing Wall")
    {
        runForwards = true;
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Use tags to specify each collider. But you can also use names of gameobject. That totally depends on you or game. \$\endgroup\$ – Saad Anees Jun 19 at 14:38
  • \$\begingroup\$ i think that if you use 'isTrigger' on one of the colliders you may need to use the method OnTriggerEnter2d() instead. Your code looks ok in that it checks the actual name of the GameObject you might collide with. But like Saad says you could just add tags in the inspector and then use collision.gameObject.tag == "Right Facing Wall" \$\endgroup\$ – Big T Larrity Jun 19 at 14:56
  • \$\begingroup\$ Also before that, try if (collision.gameObject.name) ...ie remove the '.collider' part \$\endgroup\$ – Big T Larrity Jun 19 at 14:57
  • \$\begingroup\$ I do not recommend looking up GameObjects or matching them by name. Other methods like CompareTag or checking for the presence of a particular component (which can expose additional marking data) are much more robust and less error-prone. \$\endgroup\$ – DMGregory Jun 19 at 16:10
  • \$\begingroup\$ Did you add collider components to the walls and the character? Add a rigidbody2d too. They are a requirement for triggering the OnCollisionEnter2D (only on the character) \$\endgroup\$ – Undume Jun 20 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.