- Home /
Using reflection to Invoke a UnityEvent
So, seems simple... I have a bunch of UnityEvents in my class onActionA, onActionB etc... and i want to Invoke them using their string names... because there will be a lot of them and i'm trying to avoid a massive switch statment. what i have so far is:
System.Type prefsManagerClassType = typeof(PrefsManager);
FieldInfo myFieldInfo2 = prefsManagerClassType.GetField("onChangePref_skybox_filename");
MethodInfo method = myFieldInfo2.GetType().GetMethod("Invoke");
//
//method is always null here
it is the MethodInfo line that falls down and fails to get a valid method... so i can't then Invoke it... Help! Thanks.
Answer by CodesCove · Mar 03, 2021 at 08:23 PM
Should be: MethodInfo method = myFieldInfo2.FieldType.GetMethod("Invoke");
However after this, when you actually Invoke the event via MethodInfo, you need the object instance reference so I'm not sure how this helps your case. It would look like this: method.Invoke(onChangePref_skybox_filename, null);
What you could do is to make array out of the Actions and invoke them by index or even better store them to a Dictionary and assign string names to them as Keys and events as Values. If you make array or Dictionary static you can reference them easily from anywhere in you code.
.. or then again, maybe I understood something wrong.
But anyway the first code corrects the null error. Hope this helps.
Thanks - putting them into a Dictionary is actually nice and neat and tidy
Your answer
![](https://koobas.hobune.stream/wayback/20220613030130im_/https://answers.unity.com/themes/thub/images/avi.jpg)