How to tell if GameObject is the prefab you wanted, and not some prefab that anything goes?

Say I have:

  • Cube prefab.
  • Sphere prefab.
  • Custom prefab.

And I did a Raycast on a game object that is either a Cube, a Sphere, or a Custom prefab. And one of the prefabs is the one I specify for a certain scenario requiring the player to have that prefab of a certain shape enabled and ready.

How do I tell if the game object is the prefab I wanted, and not some other prefabs?

Tag checking and name checking are the easy answers.

For something more robust and flexible, you can check if the prefab has a specific component or implements a specific interface.

You can use GameObject names, tags, or (most likely) some script that they all share but which have a different value from one prefab to the next. For instance, you make an “ObjectType” script with a public enum with options for “Cube”, “Sphere”, or “Custom”, and then shove that script on your different object-type prefabs. Then, when raycasting, you just have to say (for instance):

//raycast first, hit object would be "hit"

ObjectType typeScript = hit.GetComponent<ObjectType>();
if(typeScript)
{
    if(typeScript.type == ObjectType.TypesOfPrefabs.Sphere)
    {
        //SPHERE STUFF
    }
}

There are of course a dozen others ways to do it.

Thank you.