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.
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:
IsSubclassOf has to be used like this:
That are the major ways how to check if a certain object is of a certain type.
In more recent Untiy versions, we can now use a declaration pattern that allows you to declare a local variable inside the if-expression. That way you get a casted value that you can use inside the if body:
// example copied from Captain_Pineapple's comment
if (targetObject is Component comp)
//comp now directly contains the targetObject value casted into `Component`
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