I’ve encountered an issue where I’m setting a component’s UnityAction field via an inspector script. Because UnityAction’s are not serializable I am having trouble getting the changes to persist on play, as the SerializedObject ApplyModifiedProperties method doesn’t seem to work with these changes and I am unable to set the value via any of the available methods because UnityAction does not fit into any of the setters provided by SerializedObject
I attempted to set it by setting the value via reflection with FieldInfo’s SetValue. I verified that the value is being set by following up with a GetValue call on the object, and the UnityAction invocation list was updated as expected. However, as soon as I hit play, the UnityAction resets to null
How do you get changes made to non-serializable objects to persist on play?
UnityAction is literally just: public delegate void UnityAction(); and naturally Unity can’t serialise delegates.
UnityEvent’s base class implements the ISerializationCallbackReciever interface (alongside the class that actually handles the persistent listeners, PersistantCall), which is how it serialises it’s magic via reflection.
In the former case you’ll need to introduce your own serialisation, in the latter you just need to make sure the root UnityEngine.Object is dirtied.
I am using UnityAction. I set up a serializable class for UnityAction using a solution posted here but the issue I am currently facing is how do I set this custom property via the SerializedObject methods? Being none of SerializedObject’s getters/setters return a generic object I am unsure how to get the Serializable class to serialize within Unity.
I could use SetDirty, but this introduces problems as all my other fields set their values with the SerializedObject methods (which winds up creating a bug where any field changes from supported types (int, float, etc) will override the SerializedUnityAction).
Okay, so I found a simple solution that was introduced in 2022.1. I updated in order to use it, makes things sooo much easier when dealing with generics on SerializedObjects