- Home /
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"
//Later
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.
Thanks.
Working in Strings is very slow. Perhaps rethink the logic and register delegates ins$$anonymous$$d.
Edit: Ok fafase already mentioned delegates. I'll upvote ;)
Answer by fafase · Oct 16, 2015 at 05:59 PM
"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:
dict["MyMethod"]();
or
Action action = dict["MyMethod"];
action();
Sory to necro this post.
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);
Is there a way to automate dict.Add("MyMethod", st.MyMethod); ? Would be really to tedious to add the string, method one by one if we have dozens of function.
Answer by Herschelx · Jul 02, 2021 at 05:39 PM
You could also simply
public string funcName = "cScript.atkScript.StopAtk"
Invoke(funcName, time you want it to activate);
Your answer
Follow this Question
Related Questions
Animation events firing all at once in mirrored blend tree 1 Answer
Cannot select function for Animation Event 0 Answers
C# - parsed strings not changing in function 1 Answer
Animation Event Bug 1 Answer
2D Animation does not start 1 Answer