tflores
tflores

Reputation: 1

How to log game objects colliding in Unity

This is my first unity project so I am fairly unfamiliar with everything the platform has. I am trying to log a message to the console when I have a my player game object run into a finish line. Both objects have Box Colliders on them and I have attached a C# script to the player object. Below is the code I have currently.

 void OnCollisionEnter2D(Collision2D col)
{
     if (col.gameObject.tag == "Finish")
    {
        Debug.Log("Finish");


    }
}

The problem is that when I move the player into the "Finish" object no logging appears inside the console. Thanks in Advance!

This is the main player inspector tab

This is the finish line inspector tab

Upvotes: 0

Views: 860

Answers (3)

Programmer
Programmer

Reputation: 125275

With the updated question and screenshots, the problem is that you're checking for the "Finish" tag but the "Finish" GameObject's tag is set to "Untagged" so the if (col.gameObject.tag == "Finish") statement will not evaluate to true.

You have two options:

1. Select the "Finish" GameObject, click the tag that says "Untagged" and create new tag named "Finish". If you already have this tag, change the tag of the "Finish" GameObject from "Untagged" to "Finish" and your if (col.gameObject.tag == "Finish") code should work.


2. If you did not intend to use tag then just compare the GameObject by name instead of tag by simply replacing if (col.gameObject.tag == "Finish") with if (col.gameObject.name == "Finish").

If none of the two options above worked for you then OnCollisionEnter2D is not being called at-all. Put a Debug.Log outside the if statement like below and leave a comment about if there is a log or not.

void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log("Finish: " + col.gameObject.name);
}

Upvotes: 2

Łukasz Drzensla
Łukasz Drzensla

Reputation: 31

Your script attached to the player checks for a collision with an object with the tag "Finish". Your Object "Finish Line" has tag "untagged". You have to add a tag "Finish" to it to see it working.

Upvotes: 3

Rustam Ashurov
Rustam Ashurov

Reputation: 186

Just first idea that came in mind: - Did you add colliders on both of objects that should collide? Without them engine will not generate events of colliding at all.

Upvotes: 0

Related Questions