- Home /
Dictionary in second script empty
Hi guys,
I have a dictionary in script A that is part of a prefab which will included in script B. All key/value pairs are set in the start method of script A and I also can access them in this method.
In the second script I access the dictionary with gameobject.GetCompontent<scriptA>().dict
but the dictionary is always empty. I am realy confused. I thought it would be the late initialization but the update method shows the empty dictionary on each frame.
Thanks a lot!
Class A with the directory.
public class ScriptA : MonoBehaviour
{
public Dictionary<string, int> dict = new Dictionary<string, int>();
// Use this for initialization
void Start ()
{
dict.Add("key1", 888);
dict.Add("key2", 999);
}
}
Class B that holds an array of gameobjects. The gameobjects contains ScriptA.
public class ScriptB : MonoBehaviour
{
public GameObject[] Container;
// Use this for initialization
void Start () {
Debug.Log(Container[0].GetComponent<ScriptA>().dict.Count);
}
}
Answer by IvovdMarel · Aug 13, 2018 at 09:08 AM
Is Container[0] referencing the prefab? If you don't Instantiate the object, the Start function will never run on it.
Yes, the Container holds two prefabs.
Something like this also ends up with 0 items in the dictionary.
GameObject instance = Instantiate(Container[0]);
Debug.Log(instance.GetComponent<ScriptA>().dict.Count);
Where exactly are they being instantiated / Where is the code you put above ran? Only logical conclusion to me seems that due to script execution order or the way you have your scripts setup you might actually be reading the dictionary before start gets ran to add the values but from the code you've shown and what you've said so far that's honestly the only explanation I can think of.
Try changing your dictionary initialisation to this
public Dictionary<string, int> dict = new Dictionary<string, int>()
{
{"key1", 888},
{"key2", 999}
};
This should confirm if that is the issue.
Oh yes, you are right. I thoght it would be accessable if it is assigned in the inspector. But sure, the start method is never called. Thank you. :)