Search Unity

Calling a function by name using string in javascript

Discussion in 'Scripting' started by arcandio, Sep 9, 2012.

  1. arcandio

    arcandio

    Joined:
    Aug 30, 2009
    Posts:
    89
    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...)
     
  2. Morning

    Morning

    Joined:
    Feb 4, 2012
    Posts:
    1,141
    Last edited: Sep 9, 2012
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    There's actually many ways to do this.

    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:

    Code (csharp):
    1.  
    2. function CallFunc(obj:Object, method:String)
    3. {
    4.     var meth:System.Reflection.MethodInfo = obj.GetType().GetMethod(method);
    5.     if(meth != null) meth.Invoke(obj, null);
    6. }
    7.  
    8. function CallFunc(obj:Object, method:String, args:Object[])
    9. {
    10.     var meth:System.Reflection.MethodInfo = obj.GetType().GetMethod(method);
    11.     if(meth != null) meth.Invoke(obj, args);
    12. }
    13.  
    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:

    Code (csharp):
    1.  
    2. obj["myfuncname"](...);
    3.  
    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)
     
    Last edited: Sep 10, 2012
  4. fano_linux

    fano_linux

    Joined:
    Jan 1, 2012
    Posts:
    909
    Well in regular javascript (web) we use eval

    eval("function_name");

    I'm not a big fan of JS in unity and i don't know if eval will work at unity, but in web JS it's common to use eval function.