Serializing, Generics, and Inheritance

I’m having a hard time getting a generic monobehaviour to properly work. To do so, it’s generic fields must be serialized and show up in the editor. Here’s the relevant code for the generic monobehaviour:

public class ResultConsumer<Request,Result> : MonoBehaviour where Request : struct, IEquatable<Request> where Result : struct
{
    [SerializeField]
    private Cache resultsCache;
    [SerializeField]
    private Queue requestsQueue;
  
    [Serializable]
    public class Cache : ResultCache<Request, Result>
    {

    }
    [Serializable]
    public class Queue : RequestQueue<Request>
    {
    }
}

Here’s the relevant code for ResultCache and RequestQueue.

public class RequestQueue<Request> : MonoBehaviour where Request : struct, IEquatable<Request>
{

]
public class ResultCache<Request,Result> : MonoBehaviour where Request : struct, IEquatable<Request> where Result : struct
{

}

My goal is to allow any class to inherit from ResultConsumer and then drap n’ drop a ResultCache and RequestQueue that matches its type. However, ResultConsumer’s fields are not being serialized properly and won’t show up in the editor. Any ideas on how to circumvent this limitation?

Move the Cache and Queue classes to their own files.

Fully implement ResultConsumer.

Any type that contains a templated generic parameter in its declaration is never serializable by Unity.

1 Like