Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Thoughts on serialising a generic type

Discussion in 'Immediate Mode GUI (IMGUI)' started by Tom01098, Aug 13, 2018.

  1. Tom01098

    Tom01098

    Joined:
    Jun 8, 2015
    Posts:
    42
    Hi all, I'm writing an editor script where a user can create their own classes and then instantiate and edit objects in a GUI. A feature of this is that it will support generic classes. Of course, there becomes the problem of serialising these classes - I've already tried inheriting from ScriptableObject, but that doesn't work correctly.

    Here is an example snippet of code I would like to serialise:

    Code (CSharp):
    1. public class Example<T, U> : Base
    2. {
    3.     public T a;
    4.     public string b;
    5.     public U c;
    6. }
    'Base' is serialisable (using ISerializationCallbackReceiver) checks will occur on instantiation to make sure T and U are as well. Only serialisable values can be used within one of these generic classes.

    Now, I'm trying to think of an elegant way to serialise these values. I would ideally like them to be serialised 'in place' - by this I mean that the object is not destroyed and then recreated. However, as they are all stored inside a List<Base> I am aware that they may all get serialised as Base, which means I may have to serialise them in an external class somehow.

    Any pointers on how I may overcome this problem are highly appreciated, thank you for reading.
     
  2. BinaryCats

    BinaryCats

    Joined:
    Feb 8, 2016
    Posts:
    317
    where I am not sure of a solution that uses ISerializationCallbackReceiver, Usually when you want to serialise a generic you have to inherit from it, defining the generic types i.e.
    Code (CSharp):
    1. public class FloatIntExample : Example<float, int>
    2. {
    3. }
    4.  
    5. public FloatIntExample myvar;
    6.  
    Although this solution can lead to annoying code patterns.If there is a solution using ISerializationCallbackReceiver I am interested to hear it!
     
  3. Tom01098

    Tom01098

    Joined:
    Jun 8, 2015
    Posts:
    42
    Yes, I've seen people use that pattern before - I actually can't have users of this extension use that pattern because the extra level of inheritance complicates how the GUI will work, thank you anyway :)

    (EDIT: Also I cannot use this as in your example, float and int are both concrete, while the extension is intended for the user to choose any combination of types)
     
    BinaryCats likes this.