- Home /
UnityEvent as a serialized property
I have a field of a GameObject that is a concretized subclass of UnityEvent.
I am trying to write a property drawer for that concretized subclass.
But UnityEventBase does not seem to be a child class of Object so using property.objectReferenceValue does not return anything that I can cast to my sub-class.
How does one get the deserailized property where such a property is a subclass of UnityEvent?
Funny thing, I'm working on a tool, and I was stuck with that one today. UnityEvent's propertytype is Generic and not ObjectReference. So we can't get access to the value or change anything from any serializedProperty value field...hope someone can help us :).
Answer by Jeff-Kesselman · Jul 29, 2015 at 02:32 PM
The answer from Unity support is thus:
UnityEvent is a "normal" class, you should be able to use SerializedProperty.Next() to drill down into its data but not objectReferenceValue.
SO, I guess we have to use the SerializedProperty sub-property parsing function to get at the data.
Yes, "normal" seriaizable classes are serialized along with the containing type. If you force text-serialization in Unity you can look at any prefab or scene asset with a text editor and see how the data is actually structured. Unity can only reference things derived from UnityEngine.Object as they are serialized on their own and get a seperate instance id which can be used to reference the instance.
Answer by Acegikmo · Apr 13, 2016 at 11:58 AM
Here's a workaround that lets you access the proper UnityEvent object instead of just the serialized data
public UnityEvent GetUnityEvent(object obj, string fieldName){
if( obj != null ) {
FieldInfo fi = obj.GetType().GetField(fieldName);
if( fi != null ) {
return fi.GetValue(obj) as UnityEvent;
}
}
return null;
}
It's important to point out that if the field is private, you also have to pass NonPublic and Instance BindingFlags when using GetField, like this:
public UnityEvent GetPrivateUnityEvent(object obj, string fieldName){
if( obj != null ) {
FieldInfo fi = obj.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if( fi != null ) {
return fi.GetValue(obj) as UnityEvent;
}
}
return null;
}
Your answer

Follow this Question
Related Questions
Event System - AddListener and Callbacks 2 Answers
GUI.Window makes custom EditorWindow drag header unresponsive 2 Answers
Serialize UnityEvent for use in EditorWindow 0 Answers
How to make a function like OnEnable that fire by itself when specific event occurs? 1 Answer
Best Practice to destroy gameobject 1 Answer