Search Unity

Serialize objects while keeping references to asset

Discussion in 'Scripting' started by DoYouRockBaby, Aug 9, 2018.

  1. DoYouRockBaby

    DoYouRockBaby

    Joined:
    May 21, 2018
    Posts:
    9
    Hello World.

    (first, sorry if my english is not perfect)

    I'm trying to do a tricky serializing stuff, here is a little description of what i want to do :
    - I have got a Scriptable Object, it contains a list of other objects.
    - These object types all implement an abstract class.
    - In some of those implementation, i need to reference some assets.

    I know it could not be really understandable so I made a UML inspired diagram :
    uml.png

    But i don't manage to properly serialize my list of objects. I tried three ways for now :
    - By making my abstract class inherits of Scriptable Object : I've got "Type mismatch" in my inspector in the scriptable object list
    - By making my abstract class inherits of UnityEngine.Object : I've got "None" in my inspector in the scriptable object list
    - By using JsonUtility.Serialize/Deserialize : Everything works except that the reference to the assets are not saved when i restart Unity

    Thanks a lot for your future help :)
     
  2. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
  3. Fido789

    Fido789

    Joined:
    Feb 26, 2013
    Posts:
    343
  4. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    It's a Scriptable Object containing a list with polymorphed objects. Meaning a list of abstract class type objects, which will be filled with objects that implement the base abstract class type. Just like his UML diagram suggests.

    Something like this, Health Potion is by Core an Item but the serialization system tries to serialize it as an Item not a Health Potion. This causes it to be a type mismatch.

    Code (CSharp):
    1. public class Inventory : ScriptableObject
    2. {
    3.     public List<Item> Items;
    4. }
    5.  
    6. [Serializable]
    7. public abstract class Item
    8. {
    9.     public int ID;
    10. }
    11.  
    12. [Serializable]
    13. public class Consumable : Item
    14. {
    15.  
    16. }
    17.  
    18. [Serializable]
    19. public class HealthPotion : Consumable
    20. {
    21.     public int HealAmount = 9001;
    22. }
    Unity cannot serialize polymorphed objects... it will just show up as Type Missmatch when you add things at runtime.

    I was working on an inventory that contained a list of Items. Both were scriptable objects, but Items are polymorphed objects. Because an Item could be a Consumable, Equipment or Quest item or whatever. It's an implementation of the base class. But Unity doesn't see it as an Item but as the implemented class, causing a type mismatch.
     
    Last edited: Aug 10, 2018