I was just working on a game, and then I saw some video talking about making an event manager, so I watched it and decided to make one myself.
While doing so I found that UnityEvent really doesn’t have many methods I think it should have, so I decided to make them myself using extension methods, and then share them here. 😉
I will just paste my script here. If you understand those things, feel free to tell me how I can improve it, since I am pretty new to some of the things there (like Reflections, I literally started learning about them today). If you don’t then just make a new script and paste it there.
using UnityEngine.Events; using System; using System.Reflection; using System.Collections.Generic; public static class UnityEventExtensionMethods { /// /// Gets all the actions in the event as an IEnumerable(UnityAction). /// public static IEnumerable GetAllActionsAsEnumerable(this UnityEvent @event) { // Loop through all of the actions in the event. for (int i = 0; i < @event.GetPersistentEventCount(); i++) { // Get the information about the action. MethodInfo actionInfo = UnityEventBase.GetValidMethodInfo(@event.GetPersistentTarget(i), @event.GetPersistentMethodName(i), new Type[0]); // Cast actionInfo into a UnityAction to get the listener. yield return () => { actionInfo.Invoke(@event.GetPersistentTarget(i), null); }; } } /// /// Gets all the actions in the event as an array of UnityAction. /// public static UnityAction[] GetAllActions(this UnityEvent @event) { // Make a list of the actions that will be returned at the end. var actions = new List(); // Get all the actions as an enumerable. IEnumerable eventActions = @event.GetAllActionsAsEnumerable(); // Loop through the actions and add them to the actions list. foreach (UnityAction currentAction in eventActions) actions.Add(currentAction); // Return the list as an array. return actions.ToArray(); } /// /// Gets a specific action at the index of index. /// public static UnityAction GetAction(this UnityEvent @event, int index) { return @event.GetAllActions()[index]; } }
For anyone who is wondering…the reason the event parameter is called “@event” is because “event” is already a keyword in C#.