0
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?

1 Answer 1

1

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.