Page 1 of 1

Help with workaround on UnityEvents

Posted: Thu Oct 14, 2021 5:26 pm
by robotSmith
(Last one, sorry for the spam)

I'm using UnityEvent and ScriptableObjects Events to manage some decoupled events. I need to save this :? .

Now, from reading the forums, I realized that UnityEvent is not serializable and you gave some ideas. I having a hard time understanding how to implement the work around. Would I be able to get some guidance?

How am I using the events:
- I have a ScriptableObject with a UnityEvent (appearing on the inspector)
- I create an Event ScriptableObject that I attach to this UnityEvent
- I add a Listener Object to any object that I want to register, I add this ScriptableObject again and I register whatever method that I want to register

When I load the UnityEvent appears as null (as expected from reading the forums)

For reference the idea that was given was this:

Code: Select all

// To save
ES3.Save( "myEvent", event.GetPersistentMethodName(0) );

// To load
string methodName = ES3.Load<string>("myEvent");
event = new UnityEvent();

if(methodName == "MyMethod")
    event.AddListener(MyMethod);
if(methodName == "AnotherMethod")
    event.AddListener(AnotherMethod);
TIA!

Re: Help with workaround on UnityEvents

Posted: Thu Oct 14, 2021 5:39 pm
by Joel
Hi there,

I'm afraid I'm not sure what guidance to give except that already given in the other thread.

To rephrase what was said in the other thread in case it helps, when saving you would need to save the name of the method which is currently assigned to that Unity event. Then when loading, you would need to create a new UnityEvent object, load the name of the method that UnityEvent is using and then assign that method to the UnityEvent using the UnityEvent's AddListener method.

However, as we can't officially support UnityEvents, and how you go about this is likely to differ depending on your project, I'm afraid I wouldn't be able to provide any more assistance than this.

All the best,
Joel