Passing a rvariable from UnityEvent to all its listeners.

Excuse my poor wording, but I’m trying to have an Unity Event that returns a variable that then passes this variable to all it’s listeners (unity Actions), which are functions that uses this variable as a parameter.

I want something like this:

public class IntUnityEvent : UnityEvent<int> {};
public IntUnityEvent myEvent;
private UnityAction myAction;

private void Awake()
{
    myAction = FunctionA;
}

private void Start()
{
   myEvent.Invoke(5)
}
private Task FunctionA (int _number)
{
....do stuff with "_number".
await Task.Delay(1);
}

private void FunctionB ()
{
   if (myEvent != null)
      myEvent.AddListener(myAction);
}

Basically I want to pass the 5 to all listeners on this custom Unity Event. However, I’m not sure how I can get this to compile, or if this is even possible. I’ve not been able to get the code to compile with various errors.

Thanks for the help. :slight_smile:

Edit: I might have figured it out. I needed to add a type to the UnityAction:

UnityAction<int> myAction;

Not sure if this is doing what I want it to do, though, but at least it compiles.

public class IntUnityEvent : UnityEvent<int> {}

What’s the point of this? Why not just use a UnityEvent<int> as is what it’s designed for.

As quoted from all the Unity documentation pages, “If you wish to use a generic UnityEvent type you must override the class type.” I don’t know why you need to, but apparently you do.

1 Like

I’d assume that’s because Unity used to not be capable of serializing generics. So serializing Foo wouldn’t work, but serializing MyFoo : Foo would.

In “modern” Unity ( >2020.1 ) it should not be necessary to define IntUnityEvent, UnityEvent should be serialized just fine. I might be wrong though, so test this to make sure!

1 Like

I’m, using 2020.3+, you still have to inherit from UnityEvent with your own class in order for it to work.

What I wrote in the OP isn’t working at all.

Using a UnityEvent that has a listener with UnityAction, where t0 for both are the same variable type does not automatically pass the variable between the event and its listeners.

If Have:

IntUnityEvent myEvent; UnityAction myAction;

Start()
{
myAction = FunctionB;
myEvent?.AddListener(myAction);
}

Private Task FunctionA(someObject _object)
{
await Task.Delay(100)
myEvent?.Invoke(5);
}

Private void FunctionB(int _num)
{
Debug.Log(_num);
}

When function A is called, function B should print out the number 5 in the debug messages. But nothing happens. I’m guessing the listener isn’t getting added because myEvent is always considered null for some reason?

Any suggestions would be appreciated.

EDIT: Figured it out. I forgot to initialize myEvent with “= new inUnityEvent()”, so its conisdered a null and thus no listeners are added to it.