Home > Net >  Unity - UnityEvent<object> as parameter but pass in UnityEvent<CustomClass> not working
Unity - UnityEvent<object> as parameter but pass in UnityEvent<CustomClass> not working

Time:07-17

Not sure if this is possible, I can get this to work if I used the explicit type but if I do it that way it will require me to define every possible type, which could be a lot.

BACKGROUND:
I'm trying to add my custom generated list of unity event actions to a target unity event. This is meant to be a generic helper function that I can use in many of my automated editor scripts.

WHAT IM DOING:
I have a function that looks like the following:

public static void SetUnityEvents(UnityEvent<object> targetEvent, List<UnityEventEntry> entries, bool removeAllListeners = false)
{
  ...
}

Then I'm trying to use it like:

UnityEventsUtil.SetUnityEvents(target.GetComponent<vLadderAction>().OnDoAction, newEntry, true);

Where newEntry is a custom List<UnityEventEntry> object that contains all the unity events that I want to add to the target.GetComponent<vLadderAction>().OnDoAction UnityEvent.

However, when I pass target.GetComponent<vLadderAction>().OnDoAction UnityEvent to the function I throws the following error:

Argument 1: cannot convert from 'Invector.vCharacterController.vActions.vOnActionHandle' to 'UnityEngine.Events.UnityEvent<object>'

Like I said before I could change my above function to be:

public static void SetUnityEvents(UnityEvent<vOnActionHandle> targetEvent, List<UnityEventEntry> entries, bool removeAllListeners = false)

and it would work. However, it's no longer generic and I would need to pass in every type.

Is this possible to make something like this generic? If so how would I do that conversion?

CodePudding user response:

I was able to get it to work by not using UnityEvent<object> but instead taking advantage of the concept of generics. Helpful youtube video talking about it here: https://www.youtube.com/watch?v=LnjuFeHLQ2Y

So I converted my above function to be a generic:

public static void SetUnityEvents<T>(T unityEvent, List<UnityEventEntry> entries, bool removeAllListeners = false) where T : UnityEventBase
{
  ...
}

That requires that a UnityEvent gets passed to unityEvent and doesn't just take anything because all UnityEvents derive from UnityEventBase base. So this allows me to keep the original type and pass ANY type of unity event into this function. Even UnityEvents that take any number of parameters, including custom classes. Pretty awesome!

  • Related