Cast object to System.Object
How can I properly cast this object type of a "System.Object" type so I can access it as a "SerializedObject"?
Here is my function:
public static void CopyUnityEvents(object source)
{
SerializedObject so = new SerializedObject(source);
}
CopyUnityEvents(prefab.OnPressActionInput);
prefab.OnPressActionInput
is a UnityEvent. I want to get the parameter values while looping through this event. I have tried it via reflection but that doesn't seem to work so I have read that this should be possible via this. However, I can't seem to figure out the proper way to cast this to and Object
type to even get started down this road....
Answer by wesleywh · Aug 09, 2020 at 01:44 AM
Nevermind I'm just going to pass in the component reference instead of the UnityEvent refence like so:
CopyUnityEvents(prefab);
Answer by Bunny83 · Aug 09, 2020 at 02:02 AM
SerializedObject only works on classes derived from UnityEngine.Object. So your method would never work. UnityEvents are just serialized classes and therefore just consists of SerializedProperties of the class they are used in. So you have to create a SerializedObject of your prefab and grab the SerializedProperty / Properties from there.
That said UnityEvents are a pain to work with when it comes to SerializedProperties. A UnityEvent is composed of several other custom classes which makes it quite difficult to access the actual serialized data. For example the UnityEventBase class (which is the base class for UnityEvent) has a PersistentCallGroup. The PersistentCallGroup has a List of PersistentCall instances. Each PersistentCall has several fields.
So in order to copy / duplicate a serialized UnityEvent there's quite a bit of data you have to run through if you do that through SerializedProperties.
Oh I am aware I had everything working except grabbing the parameter values. I actually just accomplished grabbing the parameter values. So Now I am going to combine everything together and it should offer everything I have been looking for. Thanks for the heads up though!
Here is my completed script on the matter if you're interested: https://gist.github.com/wesleywh/1c56d880c0289371ea2dc47661a0cdaf