Search Unity

Adding public Dictionary as Parameter

Discussion in 'Scripting' started by magomedmirz, Jun 10, 2019.

  1. magomedmirz

    magomedmirz

    Joined:
    Jun 9, 2019
    Posts:
    9
    Hello,

    I want to add an dictionary like this:
    Code (CSharp):
    1. public Dictionary<GameObject, GameObject> mapObjs
    to my script. So I can add them in the gameObject where i added the script and match theses two gameObject's together.
    But i dont see the dictionary as parameter in the gameObject where i added the script. Did i do something wrong or is it the wrong way to approach this?

    Can someone help me out pls?
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Unity does not serialize Dictionaries, so you will not see them in the inspector. If you'd like to, you can search around for an implementation of a serializable Dictionary, or make your own. It serializes arrays and lists just fine though, so if you make a new tuple-like type like:
    Code (csharp):
    1. [System.Serializable]
    2. public struct GameObjectMap
    3. {
    4.     public GameObject ref1;
    5.     public GameObject ref2;
    6. }
    ... then use...
    Code (csharp):
    1. public List<GameObjectMap> mapObjs;
    ... then that'll work fine I think, but it obviously won't enforce unique entries or anything the way a Dictionary would.
     
    DKrayl, Rouem, rc82 and 1 other person like this.
  3. magomedmirz

    magomedmirz

    Joined:
    Jun 9, 2019
    Posts:
    9
    Thanks for your Answer!

    So I made the type you recommended and added in the start() function:

    Code (CSharp):
    1. private Dictionary<GameObject, GameObject> mapObjs = new Dictionary<GameObject, GameObject>();
    2.  
    3.     void Start()
    4.     {
    5.        
    6.         foreach(var gameObjectMap in lstObjs)
    7.         {
    8.             if (!mapObjs.ContainsKey(gameObjectMap.ref1))
    9.             {
    10.                 mapObjs.Add(gameObjectMap.ref1, gameObjectMap.ref2);
    11.             }
    12.         }
    13.     }
    It works fine as i needed, thank you!