Before I embark on this part of the journey, I thought I’d ask if people have any input on the best practice for this feature.
I’m parsing strings into a text system, and I want to give the user hooks to call functions on that object. What I basically want to do is pass in a function name as a string and call that function on the object. Right now, I’m thinking that SendMessage that doesn’t require receiver, but I’d prefer if I could check ahead of time to see if there’s a function name matching my string on the object. Is there anyway to get that kind of information from a game object? (thought, I guess such a function would return an epic number of possible functions…)
You can use ‘eval(…)’ to runtime parse code as a string. You could just mark-up a string that would end up calling the method of an object and pass it in. It’s a little slowish, but is pretty versatile. I also don’t believe it’s supported on iPhone…
There’s reflection as Morning pointed out. You could create a generic function, something like this:
function CallFunc(obj:Object, method:String)
{
var meth:System.Reflection.MethodInfo = obj.GetType().GetMethod(method);
if(meth != null) meth.Invoke(obj, null);
}
function CallFunc(obj:Object, method:String, args:Object[])
{
var meth:System.Reflection.MethodInfo = obj.GetType().GetMethod(method);
if(meth != null) meth.Invoke(obj, args);
}
There’s also ‘Invoke’ (as a member of MonoBehavior) which allows you to invoke a method on the MonoBehavior by string name and with a value to delay the call of it as well.
You could even use ‘SendMessage’ to call a function on GameObject’s and their components… but that’s also toying in the unity message system, so keep that in mind.
In most flavors of javascript you could hash out the function name to:
obj["myfuncname"](...);
but unity’s version doesn’t support this as far as I’ve tested. Probably because they compile to CIL (common intermediate language used by mono and .Net)