How to use collisions with a tag

Hello there,

when I try to use OnCollisionEnter2D without tags, it works:

void OnCollisionEnter2D(Collision2D other)
{
    moveSpeed = slowSpeed;
    Debug.Log("You damaged your car!");
}

but when trying to use it with tags (as I want the car to slow down only when colliding with houses which are tagged House but to not slow down otherwise):

void OnCollisionEnter2D(Collision2D other)
{
    if (other.tag == "House")
    {
        moveSpeed = slowSpeed;
        Debug.Log("You damaged your car!");
    }
}

I will get an error message:

Compiler Error CS1061
ā€˜Collision2Dā€™ does not contain a definition for ā€˜tagā€™ and no accessible extension method ā€˜tagā€™ accepting a first argument of type ā€˜Collision2Dā€™ could be found (are you missing a using directive or an assembly reference?).
This error occurs when you try to call a method or access a class member that does not exist.

How can I set up different behaviour when colliding with objects with different tags?

Btw. great course, I changed the behaviour a little so that you will cannot run over the customer as he has a rigid body but he has another collider around him so you just need to get close to him and also customer will point out that you do not have a package when you have none and also the game will be declared a victory when you deliver 3 packages.

Thanks

Laco

1 Like

Hi Ladislav,

Itā€™s great to see that you are already implementing your own ideas. The solution for your problem is relatively easy, and Iā€™m sure youā€™ll be able to figure it out yourself. So Iā€™m just leaving a little tip for you: Check the Collision2D class in the Unity API to see what you are able to access. Then find a way to access the tag. One little ā€œstepā€ is missing in your current if-condition.

If you cannot figure it out yourself, please let me know what you did. :slight_smile:

And in case you are in a hurry or just want to know the solution, click here for the solution.

other.gameObject.tag == "House"

How can I set up different behaviour when colliding with objects with different tags?

Like you did in your code: with if-blocks.

Did this help?


See also:

3 Likes

Perfect, thank you very much Nina.

I wish you all the best in 2022.

Laco

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms