[SerializeReference] not able to serialize System.Object field-type or string value

In the Scripting API docs, there doesn’t appear to be any restrictions on using a System.Object field with the SerializeReference attribute:

[SerializeReference]
public object AnySerializableClass = new MySerializableClass(); // should show property field for MySerializableClass

Additionally, I don’t see any restrictions in docs for setting the value to a primitive class type:

[SerializeReference]
public IComparable PrimitiveComparable = "helloThere"; // should show a TextField in editor

[SerializeReference]
public IComparable CustomComparable = new MySerializableComparable(); // shows a PropertyField for MySerializableComparable()

I can sympathize why string values aren’t serialized on a SerializeReference property. System.String isn’t marked with [Serializable]. However, strings are serializable by Unity and they aren’t derived from UnityEngine.Object.

I’m working on a build-time dependency injection framework. My use-case is serializing default values for a given type. To workaround this limitation, I’m using JSON serialization.

1 Like

[UPDATE]

If the crash is intended to be fixed, another workaround is to declare a generic wrapper in 2020.1:

public interface IObject {}

public class Wrapper<T> : IObject
{
    public T Value;

    public Wrapper(T value)
    {
        Value = value;
    }
}

// This currently crashes the editor...
[SerializeReference]
public IObject myObject = new Wrapper<int>(32);

Since the generic argument in Wrapper<> can be any object, you can serialize any value here with a big IF: if this is intended to work and the crash is fixed

1 Like

@jasonatkaruna I also reported the in32/string serialization issue here together with a weird mangement of the callbacks

Why do you say that String isn’t marked by [Serializable]?