Method Introspection in C# Classes
Being unfamiliar with C# (beyond what can be inferred from script samples and my experience writing C/etc.) I'm curious to know how to perform introspection at the class level. I would like to write an enclosure for invoking methods from my object from other classes throughout my project. If I were writing this code using php I would utilize something like:
<?php
if( method_exists( $myObject, "aMethodToCall" ) ){
// .. do something
}
?>
Objective-C has similar facilities to provide this sort of thing. From the searching I've done this evening I've seen that mono/c# provides a "Reflection" library which provides this kind of functionality but the method names in that library do not seem very explanatory.
My question is; can I perform this kind of introspection; scripting in Unity and if so could someone post a code sample or a link to a sample?
Thanks,
Thomas
Answer by tingham · Sep 13, 2010 at 12:59 AM
C#
using UnityEngine; using System.Reflection;
public class Foo : MonoBehavior {
public void Start(){
Making a call to this method is simply done as:
if( typeof(Foo).GetMethod("Bar") != null ){
Debug.Log("This class has a method named Bar");
}else{
Debug.Log("This class does not have a method named Bar; or the member is Private.");
}
if( typeof(Foo).GetMethod("FooBar") != null ){
Debug.Log("This class has a method named FooBar");
}else{
Debug.Log("This class does not have a method named FooBar; or the member is Private.");
}
It is important to note that by default; only public members are evaluated. Sending in a bitmask filter allows you to refine.
if( typeof(Foo).GetMethod("FooBar",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null ){
Debug.Log("This class has a method named FooBar and it doesn't matter if it is private or not.");
}
}
public void Bar(){
Debug.Log("Ceremonious dribble.");
}
private void FooBar(){
Debug.Log("Super-Secret Weapon");
}
}
Invoking "Bar" abstractedly from "Foo" would then look like:
Foo myFoo = new Foo(); MethodInfo myBar = typeof(myFoo).GetMethod("Bar"); myBar.Invoke(myFoo,null);
Thanks for your help, for some reason that link seemed like the toughest nut to crack earlier today. Seems obvious in hindsight, hopefully my posting some sample code is in some small way a redemptive measure.
Answer by Cyb3rManiak · Sep 12, 2010 at 11:50 PM
I'm afraid reflection is one of my weak points when it comes to C#, but I did manage to find some sample code on the forums that fits the description...
If you check out GetMethod() - notice that it will return null if the method isn't found. Either that or use GetMethods() to get the full list.
Also - Reflection is very popular, and works in Unity (and Mono) pretty much the same way as in .NET - so google is your friend in this case.