Home > OS >  UnityEventTools.AddPersistentListener not functioning as intended
UnityEventTools.AddPersistentListener not functioning as intended

Time:01-04

I'm having issues with UnityEvent.AddPersistentListener. I am trying to subscribe a function to a UnityEvent from a custom editor. The function to subscribe to the event get's called from a custom editor script inheriting from editor, and is called in a normal class structure. I get an error with what I'm trying, which makes me think it's a syntax error, but I can't figure out for sure.

Here is my code

UnityEditor.Events.UnityEventTools.AddPersistentListener(targetEvent,  delegate { UpdateAndRunPromptById(id); });

I am getting this error:

Could not register callback <UpdateSubscribedEvents>b__0 on . The class null does not derive from UnityEngine.Object

Does anyone know why this would be happening and how to fix it?

CodePudding user response:

A persistent listener is one, that will be - as the name says - persistently serialized into whoever is exposing the UnityEvent.

In order to add a persistent callback as the error is telling you the "owner" of the method to be called needs to be a UnityEngine.Object just the same way as if you would add the persistent callback the "normal" way via the Inspector.

The method needs to follow the same rules in order to be properly serialized into whoever is exposing/serializing the UnityEvent.

  • the implementing type needs to be a UnityEngine.Object
  • the method needs to be public
  • it can not be an anonymous/delegate/lambda
  • parameter has to either match the dynamic event type or be serializable into the callback

Is there a specific reason why you need to go with a persistent callback?

CodePudding user response:

I figured out a solution that works for me. Digging through the documentation I discovered that there are AddIntPersistentListener, AddStringPersistentListener, AddBoolPersistentListener, and AddFloatPersistentListener for simple 1 argumentative functions, so instead of defining the delegate (which I realized was causing the error), I just used the specific listeners as needed. For anyone wondering, this is how it looked:

 UnityEditor.Events.UnityEventTools.AddIntPersistentListener(targetEvent, UpdateAndRunPromptById, <int>);
 UnityEditor.Events.UnityEventTools.AddStringPersistentListener(targetEvent, SetGlobalFlag, <string>);
 UnityEditor.Events.UnityEventTools.AddBoolPersistentListener(targetEvent, DisplayInformation, <bool>);

I hope this helps whoever needs it.

  • Related