There is a template class

[System.Serializable] public class Point<T> { public T x { get; set; } public T y { get; set; } public Point(T x, T y) { this.x = x; this.y = y; } } 

And I'm trying to display a field in the inspector with the type of this class, but nothing is displayed in the inspector.

 [SerializeField] public Point<float> paddingContent = new Point<float>(15f, 10f); 

    1 answer 1

    Why does this problem occur?

    Inspector only works with serializable types. When the Inspector tries to draw a class inherited from MonoBehaviour, it does not work directly with the object, the first thing it does is ask the object to serialize, and then display the serialized data.

    Because of the similar work of the Inspector, the problem of displaying Generic types arises: Unity cannot serialize Generic, alas.


    How to solve this problem?

    The short answer is no , you need to write your serialization, the benefit of Unity is that it allows, but custom solutions are not good friends with native serialization, so this is a rather complicated and generally non-working option. So directly this problem is almost impossible to solve.

    But there is one loophole:

    Although Unity does not serialize GenericPoint<float> , it can serialize a class inherited from it with the substituted T type:

     public class GenericPoint<T> { [SerializeField] private T x, y; } [System.Serializable] public class GenericPointFloat : GenericPoint<float> { } 

    Unity can successfully serialize and deserialize a similar class:

     public class FoobarComponent : MonoBehaviour { public GenericPointFloat floatPoint; } 

    And since serialization was able, inspector could:

    enter image description here

    An example for the sake of (a point that has coordinates like GameObject or List does not make sense):

     [System.Serializable] public class GenericPointFloat : GenericPoint<float> { } [System.Serializable] public class GenericPointInt : GenericPoint<int> { } [System.Serializable] public class GenericPointGameObject : GenericPoint<GameObject> { } [System.Serializable] public class GenericPointList : GenericPoint<List<int>> { } 

    Add variables to the test class:

     public class FoobarComponent : MonoBehaviour { public GenericPointFloat floatPoint; public GenericPointInt intPoint; public GenericPointGameObject gameObjectPoint; public GenericPointList listPoint; } 

    And we admire the right inspector:

    enter image description here