UnityEvents + UnityActions: can't assign via code

does anyone know why this doesn’t work, and how it should be properly done?

UnityAction a = new UnityAction(PrivateMethod);
		UnityEvent uEvent = new UnityEvent();
		uEvent.SetPersistentListenerState(0, UnityEventCallState.RuntimeOnly);

In this example, the uEvent.SetPersistentListenerState throws an index out of range exception, which suggests that uEvent.AddListener failed.

How can this be done in code properly? Is there not enough of UnityEvent exposed to fully get this done in code? That is what it looks like so far to me :confused:

I’m hoping to use UnityEvents because I’d like to serialize method assignments rather than having them all assigned at runtime.

AddListener adds what they call a “Non Persistent” listener.

This means a few things depending on when/how you use it.

  1. They don’t show up in the inspector
  2. They do not persist after the end of playmode

If you want a persistent listener use UnityEditor.Events.UnityEventTools.AddPersistentListener(uEvent, a); You’ll find quite a few options in the UnityEventTools if my pseudo-code doesn’t work.

Otherwise you’re doing it correctly but there isn’t a point to set the state they are always runtime.