[SOLVED] Accessing Dictionary returns null?

I have a store class that gets all the Stores in the Scene and adds them to a dictionary.

public class Store : MonoBehaviour
        {

                public static Dictionary<string, Transform> stores = new Dictionary<string, Transform> ();

                void Awake ()
                {
                        stores.Add ("IAP", GameObject.Find ("Store - IAP").transform);
                        stores.Add ("Caster", GameObject.Find ("Store - Caster").transform);
                        stores.Add ("Spell", GameObject.Find ("Store - Spell").transform);
                        Debug.Log (stores ["IAP"]);
                        Debug.Log (stores ["Caster"]);
                        Debug.Log (stores ["Spell"]);
                        Debug.Log ("c" + stores.Count);//Prints 3!
                }

        }

Then I have my Item class (shortened for your convenience) that tries to get the values for the store dictionary (see above) but fails.

                void Start ()
                {
                        var keys = new List<string> (catalogItem.VirtualCurrencyPrices.Keys);
                        transform.localScale = new Vector3 (1, 1, 1);
                        foreach (KeyValuePair<string, Transform> kvp in Inventory.stores) {
                                Debug.Log ("b " + kvp.Value);
                        }
                        Debug.Log ("dd" + Inventory.stores.Count); // PRINTS 0!
                        //transform.SetParent (Inventory.stores [catalogItem.ItemClass]);
                        name = catalogItem.DisplayName;
//                        price = Convert.ToInt32 (keys [0]);
                        icon = Resources.Load <Sprite> ("Store/Icons/" + catalogItem.DisplayName);
                }

I don’t understand why I’m not able to access the dictionary values in the 2nd script.

[SOLVED] - Used the wrong class…

You’re trying to access Inventory.stores instead of Store.stores

1 Like

Thanks just figured that out. I was playing with the Inventory class before I decided to break it up a bit…

I can recommend you to DO NOT USE public static variables. Programmers calls it Anti-Pattern “God Object”

Is it really a “god object” though? It’s just a list of all currently active stores.

Both of them. The problem is when you use your object from different points of your programm and make some changes - it can cause undesired situations.