- Home /
Question by
ZADSAR · Jul 01, 2018 at 09:26 PM ·
2derrorscript.getcomponent
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.
Comment
Best Answer
Answer by KittenSnipes · Jul 01, 2018 at 09:29 PM
@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
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612165843im_/https://answers.unity.com/themes/thub/images/avi.jpg)