Using a string to call a function from another script without "SendMessage"

Hi everybody.

I’m trying to call functions using Animation Events and a sprite script (this manages the animations). in which I store the function names on a string array for faster work. The thing is, I could do this task using SendMessage which is faster and doesn’t require long strings of code, but I know it tends to be memory expensive and sometimes, this get executed by a lot of instances.

What I want to do is, call functions from other scripts using strings without SendMessage. I want to call functions using something like this for example:

public string funcName = "cScript.atkScript.StopAtk"


funcName(); //or something like that.

But I don’t know how can I do that, and I don’t want to write an event for every function my character needs. So, I need your help please.


“I don’t want to write an event for every function my character needs”

Wrong thinking there, short code does not mean better code. But back to your issue.

You could use reflection with GetMethod and the name of the method as parameter.
You have the script type and you get a method on it:

 Type scriptType = typeof(MyScript);
 MethodInfo info = scriptType.GetMethod("Method");
 if(info != null)  info.Invoke(obj, new object[]{});

Looks quite similar to SendMessage though.

Finally, you can have a dictionary of . For each method you need to call, you register an entry in the dictionary with a name and a delegate. For instance, you have a method MyMethod:

 Dictionary<string, Action> dict = new Dictionary<string,Action>();

 GameObject obj = GetObject(); // Get an object reference
 ScriptType st = obj.GetComponent<ScriptType>();
 dict.Add("MyMethod", st.MyMethod);

and then:



Action action = dict["MyMethod"];

You could also simply

 public string funcName = "cScript.atkScript.StopAtk"
 Invoke(funcName, time you want it to activate);