Home > OS >  C# unity implicit serialization
C# unity implicit serialization

Time:08-14

public abstract class A<T> : MonoBehaviour where T : struct
{

}

[Serializable]
public class B : A<int>
{

}

[Serializable]
public class C : A<float>
{

}

public class D : MonoBehaviour
{
    public A<int> prop; //Assignable by both C and B
}

Is it possible to assign A prop by both C and B in unity? Is there something like implicit serialization or serialize as?

CodePudding user response:

If both B and C were to inherit from A<int>, then you could assign either one to the prop field in Unity and the reference would be serialized without any issues.

You can't assign an object that derives from A<float> to a field of type A<int> though, because those are two completely different base types.

You could create an interface IA<T> and have both C and B implement IA<int>. However Unity can't handle serializing nor visualizing generic interfaces in the Inspector out of the gate.

One workaround for this would be to have the prop field's type be a non-generic class which both C and B derive from, and then you'd cast this to IA<int> at runtime. You could also use OnValidate to ensure that only instances that implement IA<int> are assigned to the field.

public class D : MonoBehaviour
{
    public A prop; //Assignable by both C and B

    private void OnValidate()
    {
        if(prop != null && !(prop is IA<int>))
        {
            Debug.LogError("Prop must implement IA<int>.");
            prop = null;
        }
    }

    private void Start()
    {
        if(prop is IA<int> intValue)
        {
            Debug.Log("Assigned value: "   intValue.Value);
        }
    }
}
  • Related