- Home /
Checking "type" of "Collider" in C#
I have objects of type "Creep" that are colliding into a trigger to be destroyed. At first, I assigned them a tag and used this conditional (which does work):
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Creep")
But I've decided I'd rather check for the type of the object colliding so I don't have to tag all future objects. I've been searching around and tried all of the following methods, none of which have worked:
if (other.GetType().ToString() == "Creep")
if (other.GetType() == Creep)
if (other is Creep)
if (other.GetType() == typeof(Creep))
Is there another way to do this that I'm not aware of? Or should one of these work and perhaps something else is causing the trouble?
Answer by Landern · Oct 13, 2014 at 03:14 AM
other is of Collider type.
The other.GameObject varoab;e is a GameObject type with a component of "Creep" on it. You will need to use GetComponent, otherwise it's a GameObject that ultimately derives at the bottom from UnityEngine.Object.
You will take a hit using GetComponent, but only you know how much it's called and whether it will be a real performance hit.
@Bored$$anonymous$$ormon +1, yes, simply put.
And just in case there is any wonder why no operator is specified in the if statement.
The internal objects(Technically UnityEngine.Object if memory serves) from Unity overload the operator "==" and method .Equals(), this is why you can put an object that derives/inherits from $$anonymous$$onoBehaviour as the condition of an if statement and it will return true (the object is not null) or false (the object is null). Some c# programmers do this on their base classes in order to save some typing checking for null.
Thanks, guys. How much of a performance hit are we talking? If I call it once every second will it be negligible, or would it be worth going the tag route even in that scenario?
Answer by Bennett-Lynch · Oct 14, 2014 at 08:01 PM
This is the code I ended up using (for anyone who stumbles upon this later down the road):
if (other.gameObject.GetComponent<Creep>())
It checks to see if the object has a component of type Creep (i.e., it has a Creep.cs script attached).
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Arongranbergs Astar DynamicGridObstacle deletes nodes from gridgraph 0 Answers
Trouble with Inaccurate Mesh Collider 0 Answers
C# Assigning EdgeCollider2D's Points 0 Answers