- Home /
Check if Object is of Type Component
I simply want to check if a Unity Object is of type Component. However, what I've tried so far doesn't work:
if (targetObject.GetType() == typeof(Component))
{
Debug.Log("This is a component.");
}
I think this has something do to with how GetType and typeof works (or fails to work) within Unity as already discussed in another question. Is there any kind of easy solution to this? I only need to do this in the editor if that helps any.
Answer by Bunny83 · Mar 10, 2017 at 06:09 AM
Well, the usual way is to use the "is" operator:
if (targetObject is Component)
Another way is to use the "as" operator. It performs a cast into the desired type. If the cast is not possible it will return null:
Component c = targetObject as Component;
if (c != null)
However if you want to use reflection and System.Type you have to use either IsAssignableFrom or IsSubclassOf. IsAssignableFrom is more flexible as it can also check interfaces and not just baseclasses.
IsAssignableFrom has to be used like this:
if (typeof(Component).IsAssignableFrom(targetObject.GetType()))
IsSubclassOf has to be used like this:
if (targetObject.GetType().IsSubclassOf(typeof(Component)))
That are the major ways how to check if a certain object is of a certain type.
Embarrassingly easy fix. Thanks. Can't believe I didn't think of that first one. Oh well. I'll try not to solve problems when I'm tired next time. Ha!
I'm just learning about the "is" operator....literally right now :)
Always makes you feel like you've acquired new power, now....what to do with it? This is what happens when you're self taught ;p
Answer by idbrii · Jan 29, 2018 at 11:52 PM
I had an Object as a MonoScript and need to use GetClass instead of GetType:
var query_as_script = query as MonoScript;
if (query_as_script != null
&& typeof(Component).IsAssignableFrom(query_as_script.GetClass()))
{
// ...
}
Your answer
Follow this Question
Related Questions
How to attach components to rigidbodies in editor 1 Answer
How can I get the Transform from an Object (target of UnityEvent)? 1 Answer
Why does my editor only render game objects that are not in the default layer? 1 Answer
Destroying Components from Editor Script Throwing MissingReferenceException 1 Answer
Copy grouped objects to another scene. 3 Answers