- Home /
Invoking UnityEvents in code and passing parameters
I've created custom buttons in Unity's UI and have added my own UnityEvents to these buttons so that I can assign functions to call on click events and such. I'm doing this with:
[System.Serializable]
public class ToggleEvent : UnityEvent<bool> { }
[SerializeField]
public ToggleEvent clickEvent;
With the event calls looking simply like:
public void ButtonEvent(bool value) { }
This works great in the editor but when I call
clickEvent.Invoke(true);
...it'll only pass whatever the bool value is marked off in the editor, not what's actually being passed. How do I override what's being set in the editor and pass my own variables in code?
Answer by Yodzilla · Nov 16, 2015 at 12:22 AM
Welp I seem to have found an ugly workaround. Instead of calling clickEvent.Invoke I can disable persistent methods and invoke the one that I want to call like so:
// this is to turn off the value and call set in the editor
clickEvent.SetPersistentListenerState(0, UnityEventCallState.Off);
clickEvent.RemoveAllListeners();
// get the method assigned in the editor and call it
MethodInfo methodInfo = UnityEventBase.GetValidMethodInfo(clickEvent.GetPersistentTarget(0), clickEvent.GetPersistentMethodName(0), new System.Type[] { typeof(bool) } );
methodInfo.Invoke(GameObject.FindObjectOfType<MenuModsScript>(), new object[] { _enabled });
I'll clean it up for sure but if anyone knows anything else I'm all ears.
additionally, from unity's manual
By default a UnityEvent in a $$anonymous$$onobehaviour binds dynamically to a void function. This does not have to be the case as dynamic invocation of UnityEvents supports binding to functions with up to 4 arguments. To do this you need to define a custom UnityEvent class that supports multiple arguments. This is quite easy to do:
[Serializable]
public class StringEvent : UnityEvent {}
By adding an instance of this to your class ins$$anonymous$$d of the base UnityEvent it will allow the callback to bind dynamically to string functions.
This can then be invoked by calling the Invoke() function with a string as argument.
UnityEvents can be defined with up to 4 arguments in their generic definition.
Your answer

Follow this Question
Related Questions
Instantiated objects into serialized property? 2 Answers
How to find property of a serializeObject that has the same name with a field of another property? 1 Answer
Error when trying to Serialize a field that is in a class 0 Answers
Should EditorGUILayout.PropertyField work with serializable classes? 1 Answer
Custom Inspector for an array of a serialized class 0 Answers