Hello,
I was wondering if there is a way to detect IF something is a MonoBehaviour… such as…
if (isMonoBehaviour) {
do code
}
Thanks,
Michael S. Lowe
Hello,
I was wondering if there is a way to detect IF something is a MonoBehaviour… such as…
if (isMonoBehaviour) {
do code
}
Thanks,
Michael S. Lowe
if (someComponent.GetType() == typeof(MonoBehaviour))
{
// Do things
}
That would return false for any class derived from MonoBehaviour. Since I’ve never seen a MonoBehaviour that wasn’t derived, it would basically always be “wrong”. This would be the appropriate way to find if an object is exactly that type and not something derived from that type.
The way to do this is to use the “is” or the “as” keywords - “is” if you only need a yes or no answer, “as” if you also plan on doing something with it if it’s true.
if (someComponent is MonoBehaviour) {
//do things
}
// OR
MonoBehaviour mb = someComponent as MonoBehaviour; //will be "null" if it isn't
if (mb != null) {
mb.enabled = true;
}
StarManta beat me to it.
He beats everybody to it.
I was really curious about this so I made a different test
public class Nope { }
public class Yep : MonoBehaviour { }
protected virtual void Start()
{
Nope nope = new Nope();
Yep yep = gameObject.AddComponent<Yep>();
if (typeof(MonoBehaviour).IsAssignableFrom(GetType()))
{
Debug.Log(string.Format("{0} {1} a {2}",
nope,
typeof(MonoBehaviour).IsAssignableFrom(nope.GetType()) ? "is" : "is not",
typeof(MonoBehaviour)));
}
if (typeof(MonoBehaviour).IsAssignableFrom(GetType()))
{
Debug.Log(string.Format("{0} {1} a {2}",
yep,
typeof(MonoBehaviour).IsAssignableFrom(yep.GetType()) ? "is" : "is not",
typeof(MonoBehaviour)));
}
if (nope is MonoBehaviour) Debug.Log("Simple NOPE is a monobehavior");
if (yep is MonoBehaviour) Debug.Log("Simple YEP is a monobehavior");
}
This was accurate and both were correct but afterwards I couldn’t figure out any time I would actually want to do this. Based on the way you have to reference them to ask the question, you will know the result without asking.
if the variable is an interface type and you are asking if the instance stored in the variable is a monobehaviour… that is one common scenario.
Why not just use typeof(variable).IsInterface?
… And how would you not know you’re talking to an interface in the first place?
The only context in which I’ve used IsAssignableFrom was when I have types that are being loaded/deserialized at runtime, and therefore I don’t know what type I’m using when I write the code.
I think he means the other way around - you have an interface, and you need to know if the interface reference you have is a monobehaviour as well.
Wouldn’t that be outside of Interface scope?
I’ve also used them in my FastReflectionExtensions class which my EventEditor scripts use.
yes its outside of the interface’s scope. however the running client code may still need to know for whichever reason.