Search Unity

Serializing, Generics, and Inheritance

Discussion in 'Scripting' started by Abbrew, Jan 13, 2019.

  1. Abbrew

    Abbrew

    Joined:
    Jan 1, 2018
    Posts:
    417
    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:
    Code (CSharp):
    1. public class ResultConsumer<Request,Result> : MonoBehaviour where Request : struct, IEquatable<Request> where Result : struct
    2. {
    3.     [SerializeField]
    4.     private Cache resultsCache;
    5.     [SerializeField]
    6.     private Queue requestsQueue;
    7.  
    8.     [Serializable]
    9.     public class Cache : ResultCache<Request, Result>
    10.     {
    11.  
    12.     }
    13.     [Serializable]
    14.     public class Queue : RequestQueue<Request>
    15.     {
    16.     }
    17. }
    18.  
    Here's the relevant code for ResultCache and RequestQueue.
    Code (CSharp):
    1. public class RequestQueue<Request> : MonoBehaviour where Request : struct, IEquatable<Request>
    2. {
    3.  
    4. ]
    Code (CSharp):
    1. public class ResultCache<Request,Result> : MonoBehaviour where Request : struct, IEquatable<Request> where Result : struct
    2. {
    3.  
    4. }
    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?
     
  2. doctorpangloss

    doctorpangloss

    Joined:
    Feb 20, 2013
    Posts:
    270
    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.
     
    Abbrew likes this.