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. Join us on Thursday, June 8, for a Q&A with Unity's Content Pipeline group here on the forum, and on the Unity Discord, and discuss topics around Content Build, Import Workflows, Asset Database, and Addressables!
    Dismiss Notice

Bug [SerializeReference] with interface and abstact class fields in Inspector

Discussion in 'Editor & General Support' started by DSivtsov, Jul 9, 2022.

  1. DSivtsov

    DSivtsov

    Joined:
    Feb 20, 2019
    Posts:
    148
    [Unity 2020.3.34f1/Windows 10 x64]
    I'm not used the [SerializeReference] before, but decided to test in on my scripts (only for testing its possibilities). The Source scripts (it was simplify and left only that demands to show the bug)
    Code (CSharp):
    1. public interface ISequenceIteration
    2. {
    3.     int Next();
    4. }
    5.  
    6. [Serializable]
    7. public abstract class SequenceIterationAbstract : ISequenceIteration
    8. {
    9. public int sequenceSize = 999;
    10.  
    11. public SequenceIterationAbstract(int size)
    12. {
    13.     this.sequenceSize = size;
    14. }
    15.  
    16. public abstract int Next();
    17. }
    18.  
    19. [Serializable]
    20. public class SequenceIterationRND : SequenceIterationAbstract
    21. {
    22.     public int zz = 5;
    23.     public SequenceIterationRND(int size) : base(size){    }
    24.  
    25. public override int Next() { //...}
    26. }
    27.  
    28. [Serializable]
    29. public class SequenceIterationNoRepeatRND : SequenceIterationAbstract
    30. {
    31.     public string ss ="sdsd";
    32.     public SequenceIterationNoRepeatRND(int size) : base(size){    }
    33.  
    34. public override int Next() { //...}
    35. }
    It was unexpected that exist the possibility to show "value" of interface and abstract fields in Inspector ("default Editor"), by this script and use the [SerializeReference] :
    Code (CSharp):
    1. public class PlayJukeBox : MonoBehaviour
    2. {
    3.     [SerializeReference]
    4.     public ISequenceIteration sequenceIteration4 =  new SequenceIterationRND(777);
    5.     [SerializeReference]
    6.     public SequenceIterationAbstract iterationAbstract5 = new SequenceIterationNoRepeatRND(333);
    7. }
    All works as mentioned except one thing if you replace values of fields (set other derived class) in script:
    sequenceIteration4 and iterationAbstract5

    the Inspector will continue to show the old values until you change the name of these fields, after that it rebuild the corresponding object ("asset") and show the right new values.
    The same behavior also in the "SerializeReferencePolymorphismExample" Example from [SerializeReference]
    It's very unexpected behavior, and i didn't found in documentation of warnings regarding it.