How to get the type of a Gameobject

Hello,

The question in its simplest form: I have a game object. How do I check if what it’s type is? If it’s a prefab called “Combat Unit”, how do I check this? I’ve tried other.getType().equals(“Combat Unit”) but this doesn’t work.

Thanks for your help!

Read on if you’d like some context!

About the game: 2D / side view. Units march across the screen, and stop to fight any enemy units or structures they encounter. Units and buildings have a rigidbody.

The problem: I’d like to implement different behaviour depending on whether the gameobject the unit encounters is an enemy unit( created from a prefab called “Combat Unit”) or a building (gameobject that is automatically present in scene). Particularly, I need units to collide, and units to halt a distance away from buildings.

What I’ve tried so far: I’ve added a child gameobject with a box collider to the unit to determine if it is close to another object with a rigidbody. Iget the scripts attached to the collision game objects. Since the scripts are different, i can check whether each is null to determine the type of the unit in the collision. This works, but I don’t think it’s good practice, and could possibly cause problems down the line as the code gets more complex.

Since a GameObject is by definition a GameObject, the type can’t be anything other than GameObject. Use tags and CompareTag.

“Since a GameObject is by definition a GameObject, the type can’t be anything other than GameObject.”

Oddly, that is actually helpful and gets a +1 from me – I needed the repetition to help with an issue of “what type of object am I dealing with”… well, now it’s obvious: it’s a GameObject, of course!
(It’s turtles all the way down…)

I know I am WAAAAY late to answer DMCH but for those who have this question in the future. If for instance you want to detect the Type of an object that another object has interacted with you could do something like the following.

    private void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.GetComponent<Character>())
        {
            Debug.Log("Character Hit");
        }
    }

This has worked for me. I’m not sure how this affects performance but I like this over using tags so that an object can be checked for more than one interaction. Only one tag can be put on a gameObject. For example if I want to check if the Character is an NPC in one instance and in another I want to check for all objects that inherit from Character, well then a tag wouldn’t work.