- Home /
Is there a better way to check for a collision with a prefab than by name or tag?
Hello,
I have set up a simple script that should destroy a game object, if it is a certain type of prefab.
[SerializeField] private GameObject rocketToKill;
private void OnTriggerEnter2D(Collider2D collision)
{
print("collided with " + collision.gameObject.name);
if (collision.gameObject.name == "playerRocket(Clone)")
{
print("rocket destroyed");
}
}
As you can see, I have set up a field in the inspector to hold a game object type, namely the only object that should be destroyed when it enters the collider. Right now I check for that by comparing the name, but I'd rather check against the type directly. Is that possible? I've already tried things like:
if (collision.gameObject == rocketToKill)
but that does not work.
I could tag the game object in question, but I reaaaally want to check against a pre defined prefab.
Answer by xxmariofer · Jan 23, 2019 at 10:26 PM
just give the prefab a tag and compare if the tag of the object is the prefab tag, you cant compare Type since a prefab isnt a type, and when doing this collision.gameObject == rocketToKill you are comparing 2 reference to 2 different objects so wont be the same.
Answer by JonPQ · Jan 24, 2019 at 07:16 PM
Check by tag, which is fairly quick, then also have a component on the objects that can be hit... so once you have confirmed the tag, you can grab the component with any extra information on it, such as what to do when its hit...
You can also control which objects collide with others in the physics settings, based on the layering. (if you wanted to get very specific control)