How do I check if the gameobject I collided with has a certain script? (C#)

Hello,

I’m trying to check if the gameobject my gameobject collided with has a certain script on it, the code is in C#.

Here is what I have right now:

void OnCollisionEnter2D(Collision2D col)
    {
        Script script = col.GetComponent<Script>();
        if (script != null)
        {
            // do stuff
        }
    }

This returns the error: CS1061 UnityEngine.Collision2D does not contain a definition for GetComponent…

What am I doing wrong and is there another way to do this?

Thanks.

@ZADSAR
That is because collisions do not contain a get component function but it has access to a game object which does. So instead you would do this:

void OnCollisionEnter2D(Collision2D col)
{
    Script script = col.gameObject.GetComponent<Script>();
    if (script != null)
    {
         // do stuff
    }
}