I made a custom object field and an Editor that allow drawing interfaces, which I am serializing using [SerializeReference],
but when I drag a monobehaviour implementing the interface and set the value of the interface field I get the error:
"Fields with [SerializeReference] cannot serialize objects that derive from Unity.Object".
Is there any way to fix this?
#Serializing interfaces using [SerializeReference]
1 messages · Page 1 of 1 (latest)
Unity does not offer a serialization implementation for direct Interface references
Is there any way for me to add serialization of interfaces, without using callback on every class implementing it?
SerializeReference can serialize interfaces just fine. What it can’t do is reference anything that inherits UnityEngine.Object, like MonoBehaviour and ScriptableObject.
It’s only for serializing classes/structs.
You could always add a wrapper object that implements your interface and accept Unity.Object
You would obviously have to add a property drawer to limit what you can drag into the field
So there is no way of serializing an interface directly without a wrapper class and have it support unity Objects?
No. I tend to use a wrapper like InterfaceObject<ISomething> which just draws one field and when you drop a ref it validates if it's of the right type and if not it just ignores it. And you can retrieve the typed ref like field.Object (yes, Object is a somewhat boring name, I know 😄 )
But i still need serializereference to serialize generics right?
You cannot support both UnityEngine.Object and Serialized POCO directly. You can do 1 or the other with a PropertyDrawer, but needs a wrapper to support both.
You do not "need" a SerializeReference if the object is a Unity Object
No, you can do private InterfaceObject<ISomething> myInterfacedUnityObject;
What I'm saying is just in case you want to work with Monos or SOs by interface... [SerializeReference] is in case you want non UnityEngine.Object serialized and displayed in the inspector (which doesn't seem to be what you want?)
(In this case InterfaceObject is a single normal class with [Serialized] attribute on top, and a <T> for the interface type)
If that's what you're after, I can throw you the code
I do this the easy way. Serialize as Monobehaviour or Component and use OnValidate to ensure it implements the interface I want.
Ofc it requires a cast at some point but it works
No I dont want non Objects to be serialized, forgot to mention it. I already made the generic wrapper but im having trouble getting the generic stored interface from the serializedProperty in the propertydrawer. So I want to extract IInterface from wrapper<IInterface> using its SerializedProperty
Here's my implementation of the thing, in case it helps you: https://gist.github.com/pulni4kiya/c28cbd4675abd7ac4fd78901ee5d3f13
With extracting IInterface I also mean just the type not the object instance
But basically, you use this.fieldInfo in your property drawer to get the type.