#Serializing interfaces using [SerializeReference]

1 messages · Page 1 of 1 (latest)

fossil flower
#

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?

elder lotus
#

Unity does not offer a serialization implementation for direct Interface references

fossil flower
#

Is there any way for me to add serialization of interfaces, without using callback on every class implementing it?

cedar sand
#

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.

flint bear
#

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

fossil flower
#

So there is no way of serializing an interface directly without a wrapper class and have it support unity Objects?

tulip spoke
#

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 😄 )

fossil flower
#

But i still need serializereference to serialize generics right?

flint bear
flint bear
tulip spoke
#

(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

obtuse crystal
#

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

fossil flower
fossil flower
#

With extracting IInterface I also mean just the type not the object instance

tulip spoke
#

But basically, you use this.fieldInfo in your property drawer to get the type.