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

Serialization and object references

Discussion in 'Editor & General Support' started by antoine-agthe, Apr 8, 2013.

  1. antoine-agthe

    antoine-agthe

    Joined:
    Nov 1, 2012
    Posts:
    15
    Consider the following example :

    Code (csharp):
    1. [Serializable]
    2. public class ClassA : ScriptableObject
    3. {
    4.     [SerializeField]
    5.     ClassB[] mBs;
    6. }
    7.  
    8. [Serializable]
    9. public class ClassB
    10. {
    11.     [SerializeField]
    12.     int mValue;
    13. }
    14.  
    15. [Serializable]
    16. public class ClassC : ScriptableObject
    17. {
    18.     [SerializeField]
    19.     ClassB mB1;
    20.     ClassB mB2;
    21.  
    22.     void Init ( ClassA lib, int index1, int index2 )
    23.     {
    24.         mB1 = lib.mBs[ index1 ];
    25.         mB2 = lib.mBs[ index2 ];
    26.     }
    27. }
    ClassA instance is the owner of ClassB instances, like a library.
    ClassC instance references ClassB instances, from a ClassA instance.

    Doing this at runtime and I have c.mB1 === a.mBs[ index1 ] and so for c.mB2.
    But when serializing, then deserializing, it seems that it's not true anymore.
    Actually, serialization makes a copy of ClassB instances and put them on ClassA and ClassC serialized objects.

    I don't wanna make ClassB extend from ScriptableObject because I don't wanna have to save ClassB instances manually with AssetDatabase.AddObjectToAsset ( eachB, a ), like I do for ClassC instances, whom I want them be directly drag'n'drop-able from the Project Window.

    Is there any way to force serialization to keep just a reference on a object ?
     
  2. antoine-agthe

    antoine-agthe

    Joined:
    Nov 1, 2012
    Posts:
    15
    Old thread, completely invalid now. Youth looks terrible when I look back ^^
     
  3. Amesh

    Amesh

    Joined:
    May 18, 2013
    Posts:
    3
    Sorry for digging up the past but I'm trying to do a similar thing whereby in a serializable object I would like to store a reference to an object in a list rather than it creating a duplicate. What has your experience taught you about this approach?