Search Unity

  1. The 2022.1 beta is now available for testing. To find out what's new, have a look at our 2022.1 beta blog post.
    Dismiss Notice

Using a dictionary in unity without serializing it.

Discussion in 'Scripting' started by RobAnthem, Jun 2, 2020.

  1. RobAnthem

    RobAnthem

    Joined:
    Dec 3, 2016
    Posts:
    80
    This is an example of how to use a dictionary in Unity without having to serialize the dictionary itself.

    Code (CSharp):
    1. public class DictionaryExampleUsage : MonoBehaviour
    2. {
    3.     [System.Serializable]
    4.     public class ObjectIDPair
    5.     {
    6.         public string ID;
    7.         public GameObject gameObject;
    8.         public string otherDataExample;
    9.         public bool someOtherData;
    10.     }
    11.     public List<ObjectIDPair> dataPairs;
    12.     public Dictionary<string, ObjectIDPair> realDictionary;
    13.     void Awake()
    14.     {
    15.         Init();
    16.     }
    17.     void Init()
    18.     {
    19.         realDictionary = new Dictionary<string, ObjectIDPair>();
    20.         foreach (ObjectIDPair pair in dataPairs)
    21.             realDictionary.Add(pair.ID, pair);
    22.     }
    23. }
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    8,306
    There are some drawbacks:
    - depending on the amount of data, this can be utterly slow on startup
    - you have the data in memory twice, waste of memory, depending on the amount of data this can be unacceptable
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    6,393
    This is a standard pattern I use all the time. If it's a small amount of data, the loading phase should be negligible. I believe you could also get around "having two copies in memory" by clearing the list after you load the data into the dictionary (this will need to be garbage collected obviously).
     
  4. SlimeProphet

    SlimeProphet

    Joined:
    Sep 30, 2019
    Posts:
    50
    What is the drawback to serializing the dictionary?
     
  5. RobAnthem

    RobAnthem

    Joined:
    Dec 3, 2016
    Posts:
    80
    This is mostly for convenience purposes. It is far more efficient to use a dictionary, but Unity doesn't serialize dictionaries, so the only way to use them without serializing it yourself and saving/loading the data when you need to edit it. This is a way to create a dictionary of something from a List or Array in inspector, just convenient is all.
     
    SlimeProphet likes this.
unityunity