Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

SerializeReference Attribute?

Discussion in '2019.3 Beta' started by SonicBloomEric, May 15, 2019.

  1. mykillk

    mykillk

    Joined:
    Feb 13, 2017
    Posts:
    60
    Not sure what's going. Haven't received a followup email with my case number and I see on the Unity issue tracker that the last issue added was over a week ago!
     
  2. LeonhardP

    LeonhardP

    Unity Technologies

    Joined:
    Jul 4, 2016
    Posts:
    3,136
    The Issue Tracker wasn't updating since September 29th which has now been fixed. Regarding the missing confirmation emails, that issue is still being investigated.
     
    Peter77 likes this.
  3. Roni92pl

    Roni92pl

    Joined:
    Jun 2, 2015
    Posts:
    396
    Does that mean inspector will be able to finally display interfaces fields?
     
  4. mykillk

    mykillk

    Joined:
    Feb 13, 2017
    Posts:
    60
    Were submitted bugs still being received and reviewed? Or do I have to report this bug yet again?
     
  5. AlkisFortuneFish

    AlkisFortuneFish

    Joined:
    Apr 26, 2013
    Posts:
    973
    Check your bug feed by looking at the fogbugz link for any other bug you have submitted. If it shows on the bottom left, yes, otherwise it has not been received.
     
    Last edited: Oct 10, 2019
    LeonhardP likes this.
  6. AlkisFortuneFish

    AlkisFortuneFish

    Joined:
    Apr 26, 2013
    Posts:
    973
    Yes, provided you use [SerializeReference] on the field.
     
  7. bsymon

    bsymon

    Joined:
    Dec 11, 2016
    Posts:
    18
    Hi !

    I was playing around with this new feature, but I may have an issue. I tried to "SerializedReference" a System.Object, but it doesn't work.

    I'm on the latest beta 2019.3.0b6.

    Here is my code, really simple :

    Code (CSharp):
    1. [SerializeReference]
    2. private object valueTest = default;
    I was expecting to something to show up in the Inspector, just the name of the property, but nothing's here ... I tried a custom editor, and grab a SerializedProperty of the field, but it returns null.

    Is it an expected behaviour, like System.Object can't be serialized ??
     
  8. tsukimi

    tsukimi

    Joined:
    Dec 10, 2014
    Posts:
    80
    Hello!

    The new attribute is really exciting, and I'm trying to work on this new fantastic serializing feature.

    It says that you can have null value for Serialized Reference Field, but when I do:
    Code (CSharp):
    1.  public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
    2.     if(some condition property should be reset to null...)
    3.         property.managedReferenceValue = null;
    4. }
    in a custom PropertyDrawer, it comes up with an error of NullRefectenceException:
    Code (Boo):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. UnityEditor.SerializedProperty.set_managedReferenceValue (System.Object value)
    Is this an expected behaviour ,or should I report as a bug?
     
  9. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    Hi. Thanks for trying the feature, this is a known bug, it should work in the future.
     
    Catsoft-Studios, Prodigga and tsukimi like this.
  10. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    Don't suppose SerializedReference will be back-ported to 2019.2?
     
  11. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    No sorry, we avoid backporting features.
    This feature is also still being stabilised.
     
  12. Bastienre4

    Bastienre4

    Joined:
    Jul 8, 2014
    Posts:
    191
    Hello. I'm trying to use the [SerializeReference] attributes in my project. Unfortunatly, it makes the editor crash when I use the inspector to change a non serialize reference field like material reference or a enum field.
    The editor log doesn't say Unity crashed.
    I have reported a bug (1194244).
    Do you have any idea what could happen?
    Thanks and have a nice day
     
    artemio_morales likes this.
  13. AlkisFortuneFish

    AlkisFortuneFish

    Joined:
    Apr 26, 2013
    Posts:
    973
    Well, an editor crash is never treated as an acceptable bug, so it’ll be fixed is what will happen! ;-)
     
  14. Bastienre4

    Bastienre4

    Joined:
    Jul 8, 2014
    Posts:
    191
    Haha.
    I meant, do you have an idea what causes the crash and is there a workaround? :D
     
  15. print_helloworld

    print_helloworld

    Joined:
    Nov 14, 2016
    Posts:
    231
    Some type tree corruption related bug here: 1194488
    This seems to only happen if the serialized field is inside a class that doesnt inherit from MB or SO.
    There was also another crash that only occurs in a build relating to SerializeReference attribute and collections, does anyone else experience this?

    Hey @tsukimi if youre trying to change the object in the inspector, for now you can do so by setting the field directly (by using propertyPath and serializedObject.targetObject) and then dirtying the object.
     
  16. Log_N

    Log_N

    Joined:
    Jun 17, 2015
    Posts:
    7
    I've also experienced crashed and freezes (issue submitted) while trying to use [SerializeReference], but it is not always has same crash callback. Basically I have SO object with some data and [SerializeReference] array of custom classes. When I change any string in my SO object it does:
    - in most cases corrupt all data inside [SerializeReference] array instances;
    - if there is reference field in my custom class, it would result in crash (particularly if it is string and editor would try to present corrupted reference).
    Sometimes I see m_ByteOffset something-something error messages briefly before crash, which somewhat confirms that it is likely an issue with memory layout on native side.

    Code (CSharp):
    1. [........Utility/SerializedProperty.cpp line 1578]
    2. Assertion failed on expression: 'm_ByteOffset + m_TypeTreeIterator->m_ByteSize <= m_Data->size()'
    This feature is frankly unusable as it is done now, shame unity does not provide source code as UE does, so it would be possible to try to fix it myself.
     
  17. AlkisFortuneFish

    AlkisFortuneFish

    Joined:
    Apr 26, 2013
    Posts:
    973
    Do remember that this is a beta and the whole point of it is to fix those issues. Pretty sure both of those are related to a bug I reported, and that was already marked as a dupe and is being worked on.
     
    SonicBloomEric and karl_jones like this.
  18. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    This is a known issue which we already have a fix for. It should be out soon.
     
    phobos2077, Log_N and SonicBloomEric like this.
  19. Log_N

    Log_N

    Joined:
    Jun 17, 2015
    Posts:
    7
    Yeah I get that. We may have different expectations of Beta stability, I would expect that feature in Beta branch (in contrast to Alpha) would be tested against normal usage. I do not mean to be negative though - it is a lesson.

    I'm happy to hear that fix would be out soon. It is an extremely useful feature that I'm very much looking forward to using, especially with support for the generics.
     
  20. toomasio

    toomasio

    Joined:
    Nov 19, 2013
    Posts:
    199
    I just wanted to thank you guys for implementing this. Seeing this work brought me tears of joy.
    Making custom editors is going to be 5x easier now.

    I made a little test if anyone wants to see how revolutionary this is for building Unity editors.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Linq;
    5. #if UNITY_EDITOR
    6. using UnityEditor;
    7. #endif
    8.  
    9.  
    10. public interface IFruit
    11. {
    12. }
    13.  
    14. public abstract class Fruit : IFruit
    15. {
    16.     public string fruitName;
    17. }
    18.  
    19. [System.Serializable]
    20. public class Apple : Fruit
    21. {
    22.     public enum AppleType { Gala, GrannySmith, RedDelicious }
    23.     [SerializeField] private AppleType appleType = default;
    24. }
    25.  
    26. [System.Serializable]
    27. public class Orange : Fruit
    28. {
    29.     public enum OrangeType { Valencia, Blood, Jaffa }
    30.     [SerializeField] private OrangeType orangeType = default;
    31. }
    32.  
    33. public class InspectorTesting : MonoBehaviour
    34. {
    35.     [SerializeReference] public List<IFruit> fruits = new List<IFruit>();
    36. }
    37.  
    38. #if UNITY_EDITOR
    39.  
    40. [CustomEditor(typeof(InspectorTesting))]
    41. public class InspectorTestingEditor : Editor
    42. {
    43.     private InspectorTesting source;
    44.     private SerializedObject sourceRef;
    45.     private SerializedProperty fruits;
    46.  
    47.     private int dropDownSelection;
    48.     private System.Type[] types;
    49.     private string[] names;
    50.  
    51.     private void OnEnable()
    52.     {
    53.         source = (InspectorTesting)target;
    54.         sourceRef = serializedObject;
    55.  
    56.         GetProperties();
    57.     }
    58.  
    59.     void GetProperties()
    60.     {
    61.         types = GetAllOfInterface(typeof(Fruit));
    62.         names = new string[1];
    63.         names[0] = "Add A Fruit!";
    64.         names = names.Concat(GetAllOfInterfaceNames(typeof(Fruit))).ToArray();
    65.         fruits = sourceRef.FindProperty("fruits");
    66.     }
    67.  
    68.     public override void OnInspectorGUI()
    69.     {
    70.         DisplayProperties();
    71.         sourceRef.ApplyModifiedProperties();
    72.     }
    73.  
    74.     void DisplayProperties()
    75.     {
    76.         dropDownSelection = EditorGUILayout.Popup(dropDownSelection, names);
    77.         if (dropDownSelection != 0)
    78.         {
    79.             var fruit = System.Activator.CreateInstance(types[dropDownSelection - 1]) as Fruit;
    80.             fruit.fruitName = fruit.GetType().Name;
    81.             source.fruits.Add(fruit);
    82.             dropDownSelection = 0;
    83.         }
    84.  
    85.         EditorGUILayout.PropertyField(fruits, true);
    86.     }
    87.  
    88.     string[] GetAllOfInterfaceNames(System.Type _interfaceType)
    89.     {
    90.         return GetAllOfInterface(_interfaceType)
    91.             .Select(x => x.Name)
    92.             .ToArray();
    93.     }
    94.  
    95.     System.Type[] GetAllOfInterface(System.Type _interfaceType)
    96.     {
    97.         return System.AppDomain.CurrentDomain.GetAssemblies()
    98.             .SelectMany(s => s.GetTypes())
    99.             .Where(x => _interfaceType.IsAssignableFrom(x) && x != _interfaceType && !x.IsAbstract)
    100.             .OrderBy(x => x.Name)
    101.             .ToArray();
    102.     }
    103.  
    104. }
    105.  
    106. #endif


    Any chance popup menus for enums will be implemented as default in the future?
     
    TheMightyRico and KWaldt like this.
  21. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    Its a known bug, we should have a fix for it in the future.

    Glad you are enjoying the feature :)
     
    toomasio likes this.
  22. heiko-achilles

    heiko-achilles

    Joined:
    Nov 11, 2016
    Posts:
    1
    Hi.

    How is it supposed to work in an Editor class?
    SerializedProperty.managedReferenceValue is write-only, so how is the serialized class instance accessible from within an Editor class?
     
  23. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    Yes, the SerializedProperty is lacking some API when dealing with managed references at the moment.
    You can still get to the properties via normal serialized Properties, you can not get the actual instance via a SerializeProperty which makes it very hard to actually share references in a generic way with an editor. We are working on improving this.
     
  24. mykillk

    mykillk

    Joined:
    Feb 13, 2017
    Posts:
    60
    An update on this. It looks like my bug report did in fact make it through to the engineering team. They just got back to me that this is expected behavior. Unity's serialization system does not support self-referencing class fields. The recommended workaround is to use an Interface instead, the same as what I demonstrated.

     
    print_helloworld and karl_jones like this.
  25. SonicBloomEric

    SonicBloomEric

    Joined:
    Sep 11, 2014
    Posts:
    1,090
    @karl_jones If it's not already, this is one of those gory details that should definitely be documented...
     
    LazloBonin and karl_jones like this.
  26. AlkisFortuneFish

    AlkisFortuneFish

    Joined:
    Apr 26, 2013
    Posts:
    973
    I wonder why. It makes sense without SerializeReference, as it would cause infinite serialization depth without null support, but surely this stops any sort of linked list from being serialized?

    Edit: is the root of this serialized by reference itself? I’m not at work to test this, but I would expect it not to work if the root is not.
     
  27. print_helloworld

    print_helloworld

    Joined:
    Nov 14, 2016
    Posts:
    231
    @karl_jones are you able to confirm that the type tree related issues are linked to the sharedassets file being corrupted in builds and causing a crash on launch? Thanks to you and the team for this work btw, cheers.
     
  28. mykillk

    mykillk

    Joined:
    Feb 13, 2017
    Posts:
    60
    My guess is that there's probably still a lot of shared code path between SerializeField and SerializeReference. But I agree, it should be possible to have self-referencing class fields when using SerializeReference as it circumvents the issue at hand (infinite serialization depth) entirely. Perhaps that is something that can be changed eventually in a later release of Unity?
     
  29. LazloBonin

    LazloBonin

    Joined:
    Mar 6, 2015
    Posts:
    813
    Another neat perk of [SerializeReference] I just discovered is that it isn't constrained to the arbitrary maximum serialization depth of 7. Which may seem obvious considering it can be self-referencing, but it's also great for those complex nested type structures *without* self-referencing that you couldn't even serialize before because they went too deep.

    For example, this code used to fail to serialize Layer8.tooDeep and show :

    Screen Shot 2019-11-12 at 12.02.18 AM.png

    Code (CSharp):
    1. using UnityEngine;
    2. using System;
    3.  
    4. public class Depth : MonoBehaviour
    5. {
    6.     [SerializeField]
    7.     public Layer0 layer0 = new Layer0();
    8. }
    9.  
    10. [Serializable]
    11. public sealed class Layer0
    12. {
    13.     [SerializeField]
    14.     public Layer1 layer1 = new Layer1();
    15. }
    16.  
    17. [Serializable]
    18. public sealed class Layer1
    19. {
    20.     [SerializeField]
    21.     public Layer2 layer2 = new Layer2();
    22. }
    23.  
    24. [Serializable]
    25. public sealed class Layer2
    26. {
    27.     [SerializeField]
    28.     public Layer3 layer3 = new Layer3();
    29. }
    30.  
    31. [Serializable]
    32. public sealed class Layer3
    33. {
    34.     [SerializeField]
    35.     public Layer4 layer4 = new Layer4();
    36. }
    37.  
    38. [Serializable]
    39. public sealed class Layer4
    40. {
    41.     [SerializeField]
    42.     public Layer5 layer5 = new Layer5();
    43. }
    44.  
    45. [Serializable]
    46. public sealed class Layer5
    47. {
    48.     [SerializeField]
    49.     public Layer6 layer6 = new Layer6();
    50. }
    51.  
    52. [Serializable]
    53. public sealed class Layer6
    54. {
    55.     [SerializeField]
    56.     public Layer7 layer7 = new Layer7();
    57. }
    58.  
    59. [Serializable]
    60. public sealed class Layer7
    61. {
    62.     [SerializeField]
    63.     public Layer8 layer8 = new Layer8();
    64.  
    65.     [SerializeField]
    66.     public string stillGood = "Yay";
    67. }
    68.  
    69. [Serializable]
    70. public sealed class Layer8
    71. {
    72.     [SerializeField]
    73.     public string tooDeep = "oh no";
    74. }
    But if you replace any of the [SerializeField] by [SerializeReference] in that chain, then you can get tooDeep to show up and serialize:

    Screen Shot 2019-11-12 at 12.03.36 AM.png

    Now if only this crash could get fixed I'd start using it everywhere!
     
  30. Catsoft-Studios

    Catsoft-Studios

    Joined:
    Jan 15, 2011
    Posts:
    703
    This is amazing. I've been playing around with polymorphic data serialization and it works like charm. Huge thanks to the whole team.

    One question though, and pardon if I say something stupid, but i just want to clear any confusion. So the thing is that to set an integer variable from a
    SerializedProperty
    all you have to do is use the
    intValue
    . Same if you want to set a string, but using the
    stringValue
    . If you want to set an object that inherits from
    UnityEngine.Object
    (ScriptableObjects, MonoBehaviors or any Unity Component) you use
    objectReferenceValue
    .

    Up until now all clear. However, if you want to set a new instance of MyCat from a SerializedProperty, you have to use
    managedReferenceValue
    ? Doesn't "managed reference" mean there's a C++ counterpart object? Shouldn't it be named something like
    genericReferenceValue
    ?

    Code (CSharp):
    1. [Serializable]
    2. public class MyCat : Animal
    3. {
    4.     public int lifes = 9;
    5. }
     
  31. AlkisFortuneFish

    AlkisFortuneFish

    Joined:
    Apr 26, 2013
    Posts:
    973
    No, rather the opposite. Managed means it's in .Net/Mono/C# land.
     
    karl_jones and Catsoft-Studios like this.
  32. Catsoft-Studios

    Catsoft-Studios

    Joined:
    Jan 15, 2011
    Posts:
    703
    Thanks! I got this the other way around then
     
  33. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    Generic serialization such as ISomeInterface<SomeThing> is not currently supported, it's a separate issue from SerializeReference. We do have some changes coming in 2020 which will allow generic serialization.
     
  34. tsukimi

    tsukimi

    Joined:
    Dec 10, 2014
    Posts:
    80
    It seems to cause bug sometimes when below condition is fulfilled:
    ・prefabs containing [SerializeReference] List<ISomething> has different size in asset and in scene

    at first I thought they were separate bugs, so I reported separately, sorry. (case 1201620, 1201627 and 1201633)

    example:
    1. list with size=0 in prefab-asset v.s. list with size>0 in prefab-instance
    unity won't serialize list in prefab-instance, and will force the size to become 0 after enter play-mode; or unity crashes
    2. list with size>0 in prefab-asset v.s. list with size=0 in prefab-instance
    unity crashes
    3. list with size>0 in prefab-asset v.s. list with size=0 in prefab edit-mode
    you can't save prefab edit-mode list size into prefab-asset

    (however, both size=0 or both size>0 is OK)
     
    Last edited: Nov 28, 2019
    kyuskoj and karl_jones like this.
  35. Yukken

    Yukken

    Joined:
    Jul 12, 2015
    Posts:
    93
    Does [serializeRefernce]
    Which quarter of 2020 is the expected release date for that?

    My other question is a bit separate from serialised refs. When you're using serialised refs you're most likely going to change the object the serialised reference field is going to refer to. I've looked around and it seems that there is no easy way to make undo work with that. Will there be an update to the serialisedObject API to allow for easy undos for situations like this?

    If not please consider it. Unity's finally working towards a better serialisation systems but there are many issues holding us back from replacing custom serialisation solutions with built-in unity options.
     
  36. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    No exact date that I am aware of although Q1 2020 is likely.

    This issue has already been raised, we are looking at improving this. Thanks for raising it though.
     
  37. Yukken

    Yukken

    Joined:
    Jul 12, 2015
    Posts:
    93
    I haven't tried out 2019.3f1 but I've experienced massive editor slowdown issues with projects that use [serializedReference] in the last beta version.

    I have a scene with 100~ gameobjects and the editor is still snappy after upgrading to the beta. I don't use serialized ref in this project.

    On my test project I have a small amount of classes with serialized ref usage, The editor gets extremely sluggish when switching between objects. The scene only has a handful of objects. If it matters, I am also getting the 'generating diff' error messages occasionally.

    Additionally, using [serializefield] [serializedreference] on a list<SomeInterface> caused a crash. Removing serializefield solved it(I forgot to remove it before adding[serializedreference]).

    Not sure if these are reported issues. For the time being I will steer away from using [serializedreference] actively in my projects.
     
    print_helloworld and tsukimi like this.
  38. kyuskoj

    kyuskoj

    Joined:
    Aug 28, 2013
    Posts:
    56
    Code (CSharp):
    1. public class MyClass
    2. {
    3.     [SerializeReference] public ClassA a;
    4. }
    5. List<MyClass> list;
    6.  
    7. list.Add(new MyClass { a = new ClassB }); // ClassB : ClassA
    8. list.Add(new MyClass { a = new ClassA });
    9.  
    10. public class ClassADrawer : PropertyDrawer
    11. public class ClassBDrawer : PropertyDrawer
    In this situation, all element in the list is binded to ClassBDrawer. (order matters)
    Does element of IEnumerable cannot have individual PropertyDrawer?
    btw the version is 2019.3.0f1. Thanks.
     
    Last edited: Dec 2, 2019
  39. LeonhardP

    LeonhardP

    Unity Technologies

    Joined:
    Jul 4, 2016
    Posts:
    3,136
    Could you please submit a bug report for this issue, ideally with a small reproduction project?
     
  40. yu_yang

    yu_yang

    Joined:
    May 3, 2015
    Posts:
    85
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. #if UNITY_EDITOR
    5. using UnityEditor;
    6. #endif
    7.  
    8. [Serializable]
    9. public class Data
    10. {
    11.     public int a;
    12.     [NonSerialized] public int b;
    13. }
    14.  
    15. public class TestBehaviour : MonoBehaviour
    16. {
    17.     [SerializeReference]
    18.     public Data data;
    19.  
    20.     public int a;
    21.     [NonSerialized] public int b;
    22.  
    23. #if UNITY_EDITOR
    24.  
    25.     [ContextMenu("New Data")]
    26.     void NewData()
    27.     {
    28.         data = new Data();
    29.     }
    30.  
    31.     [CustomEditor(typeof(TestBehaviour))]
    32.     class TestEditor : Editor
    33.     {
    34.         public override void OnInspectorGUI()
    35.         {
    36.             var t = target as TestBehaviour;
    37.        
    38.             if (t.data != null)
    39.             {
    40.                 Debug.Log("data.a: " + t.data.a + ", data.b: " + t.data.b + ";    a: " + t.a + ", b: " + t.b);
    41.             }
    42.  
    43.             base.OnInspectorGUI();
    44.  
    45.             if (t.data != null)
    46.             {
    47.                 t.data.b++;
    48.                 t.b++;
    49.             }
    50.         }
    51.     }
    52.  
    53. #endif
    54. }
    55.  
    data.b
    &
    b
    are always modified together, they should always have same value.
    But when I change
    a
    on inspector:
    upload_2019-12-4_22-34-39.png

    So is this expected behavior?

    -------------

    I just remove
    [SerializeReference]
    and everything is back to normal. I think the behaviour of
    SerializeReference
    is unacceptable.
     
    Last edited: Dec 4, 2019
  41. print_helloworld

    print_helloworld

    Joined:
    Nov 14, 2016
    Posts:
    231
    @yu_yang so by changing the field a the entire structure gets reset/reinstanced? This might be related to the fact that unity serializes classes as structs, so changing the value of a, unity recreates the data value as its completely new now according to it, and because b isn't serialized it just goes back to its default value.
     
  42. yu_yang

    yu_yang

    Joined:
    May 3, 2015
    Posts:
    85
    I guess this is a bug, because
    SerializeReference
    is designed for 'reference', it should not recreate object unless I do it manually.
     
    print_helloworld likes this.
  43. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,300
    Please file a bug report for this
     
  44. yu_yang

    yu_yang

    Joined:
    May 3, 2015
    Posts:
    85
    case's ticket: 1203135
     
    Last edited by a moderator: Dec 5, 2019
    LeonhardP and karl_jones like this.
  45. Deleted User

    Deleted User

    Guest

    Hello everyove!
    I've got problem with [SerializedReference] attribute. Unity editor crashes after using list with attribute SerializedReference in scriptable object fields. Version of editor - Unity 2019.3.0f1

    Code (CSharp):
    1.  
    2. [Serializable]
    3. public class Animal
    4. {
    5.     public int Age;
    6.     public string Name;
    7. }
    8.  
    9. [Serializable]
    10. public class Dog : Animal
    11. {
    12.     public bool CanSayWoof;
    13.  }
    14.  
    15. [Serializable]
    16. public class Lion : Animal
    17. {
    18.     public bool IsKing;
    19. }
    20.  
    21. [Serializable]
    22. public class Zoo
    23. {
    24.     [SerializeReference]
    25.     public List<Animal> Animals = new List<Animal>();
    26.  
    27.     public void AddDog(Dog dog)
    28.     {
    29.         Animals.Add(dog);
    30.     }
    31.  
    32.     public void AddLion(Lion lion)
    33.     {
    34.         Animals.Add(lion);
    35.     }
    36. }
    37.  
    38. public class City : ScriptableObject
    39. {
    40.     public List<Zoo> Zoos = new List<Zoo>();
    41.  
    42.     [MenuItem("City/Create")]
    43.     public static void CreateCity()
    44.     {
    45.         var asset = CreateInstance<City>();
    46.         AssetDatabase.CreateAsset (asset, "Assets/NewZoo.asset");
    47.  
    48.         AssetDatabase.SaveAssets ();
    49.         AssetDatabase.Refresh();
    50.     }
    51. }
    52.  
    So when i choose created asset in project tab editor crashes.

    Already reported bug with this issue(Case 1203530). Hope it will be fixed soon.
     
  46. stevencaron

    stevencaron

    Joined:
    May 4, 2019
    Posts:
    1
    Maybe I am missing something but making the list of Zoos a SerializableReference works for me...

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEditor;
    5. using UnityEngine;
    6.  
    7. [Serializable]
    8. public class Animal
    9. {
    10.     public int Age;
    11.     public string Name;
    12. }
    13.  
    14. [Serializable]
    15. public class Dog : Animal
    16. {
    17.     public bool CanSayWoof;
    18. }
    19.  
    20. [Serializable]
    21. public class Lion : Animal
    22. {
    23.     public bool IsKing;
    24. }
    25.  
    26. [Serializable]
    27. public class Zoo
    28. {
    29.     [SerializeReference]
    30.     public List<Animal> Animals = new List<Animal>();
    31.  
    32.     public void AddDog(Dog dog)
    33.     {
    34.         Animals.Add(dog);
    35.     }
    36.  
    37.     public void AddLion(Lion lion)
    38.     {
    39.         Animals.Add(lion);
    40.     }
    41. }
    42.  
    43. public class City : ScriptableObject
    44. {
    45.     [SerializeReference]
    46.     public List<Zoo> Zoos = new List<Zoo>();
    47.  
    48.     [MenuItem("City/Create")]
    49.     public static void CreateCity()
    50.     {
    51.         var asset = CreateInstance<City>();
    52.         AssetDatabase.CreateAsset(asset, "Assets/NewZoo.asset");
    53.  
    54.         AssetDatabase.SaveAssets();
    55.         AssetDatabase.Refresh();
    56.  
    57.         Zoo BronxZoo = new Zoo();
    58.         Dog cujo = new Dog();
    59.         cujo.Age = 12;
    60.         cujo.Name = "Cujo";
    61.         cujo.CanSayWoof = true;
    62.         BronxZoo.AddDog(cujo);
    63.  
    64.         Lion cub = new Lion();
    65.         cub.Age = 2;
    66.         cub.Name = "Kimba";
    67.         cub.IsKing = true;
    68.  
    69.         BronxZoo.AddLion(cub);
    70.  
    71.         asset.Zoos.Add(BronxZoo);
    72.     }
    73. }
    74.  
     

    Attached Files:

    Catsoft-Studios likes this.
  47. Freaking-Pingo

    Freaking-Pingo

    Joined:
    Aug 1, 2012
    Posts:
    310
    I have reported a bug related to SerializeReference. Case: 1203848

    If you try to serialize an instance that implements an interface and that instance does not contain any fields that require serialization the reference is lost upon opening and closing Unity.

    If you use the following code:
    1: Create an instance of Bug_ScriptableObject
    2: Run CreateInstance
    3: Run print (notice it prints: "TestInstance")
    4: Close and reopen Unity
    5: Run print again (Now it prints "Null")
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. [CreateAssetMenu(fileName = "Bug_ScriptableObject", menuName = "ScriptableObjects/Bug_ScriptableObject", order = 1)]
    4. public class Bug_ScriptableObject : ScriptableObject
    5. {
    6.     [SerializeReference]
    7.     public TestInterface interfaceField;
    8.  
    9.     [ContextMenu("Create Instance")]
    10.     public void CreateInstance()
    11.     {
    12.         interfaceField = new TestInstance();
    13.     }
    14.  
    15.     [ContextMenu("Print")]
    16.     public void Print()
    17.     {
    18.         Debug.Log(interfaceField);
    19.     }
    20. }
    21.  
    22. [System.Serializable]
    23. public class TestInstance : TestInterface { }
    24.  
    25. public interface TestInterface { }
    But the above issue can be fixed by adding a single variable that requires serialization:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. [CreateAssetMenu(fileName = "Fix_ScriptableObject", menuName = "ScriptableObjects/Fix_ScriptableObject", order = 1)]
    4. public class Fix_ScriptableObject : ScriptableObject
    5. {
    6.     [SerializeReference]
    7.     public Fix_TestInterface interfaceField;
    8.  
    9.     [ContextMenu("Create Instance")]
    10.     public void CreateInstance()
    11.     {
    12.         interfaceField = new Fix_TestInstance();
    13.     }
    14.  
    15.     [ContextMenu("Print")]
    16.     public void Print()
    17.     {
    18.         Debug.Log(interfaceField);
    19.     }
    20. }
    21.  
    22. [System.Serializable]
    23. public class Fix_TestInstance : Fix_TestInterface
    24. {
    25.     public int someValue = 5;
    26.  
    27.     public int GetValue
    28.     {
    29.         get
    30.         {
    31.             return someValue;
    32.         }
    33.     }
    34. }
    35.  
    36. public interface Fix_TestInterface
    37. {
    38.     int GetValue { get; }
    39. }
     
    yu_yang, Peter77 and phobos2077 like this.
  48. Elringus

    Elringus

    Joined:
    Oct 3, 2012
    Posts:
    483
    I wonder if a System.Object field can be serialized (given the actual value type is serializable)?

    I mean something like the following:

    Code (CSharp):
    1. [System.Serializable]
    2. public class Data
    3. {
    4.     [SerializeReference]
    5.     public object Value;
    6. }
    I've tried it, but the value is nulled after de-serialization.

    Is this a known bug or by design?
     
    Last edited: Dec 8, 2019
  49. Deleted User

    Deleted User

    Guest

    Hi, try to create empty zoo list :)
     
  50. LeonhardP

    LeonhardP

    Unity Technologies

    Joined:
    Jul 4, 2016
    Posts:
    3,136
    This issue should be fixed in 2019.3.0f1 and 2020.1.0a15.
     
    Catsoft-Studios likes this.