- Home /
my referenced dictionary is empty on another script ,my referenced dictionary from another script dont have any key
My dictionary that I called from another code is empty. how can i solve this
script Test :
public class Test : MonoBehaviour
{
public ItemList jsonKey;
string path;
string jsonText;
public Dictionary<string, string> itemDic= new Dictionary<string, string>();
public void Start()
{
path = Application.streamingAssetsPath + "/turkish.json";
jsonText = File.ReadAllText(path);
jsonKey = JsonUtility.FromJson<ItemList>(jsonText);
for (int i = 0; i < jsonKey.itemList.Length; i++)
{
itemDic.Add(jsonKey.itemList[i].key, jsonKey.itemList[i].value);
}
}
}
script TestLoader:
public class TestLoader : MonoBehaviour
{
public Test test;
public string keyName;
public void Start()
{
GameObject tempObj = GameObject.Find("Localization Manager");
test = tempObj.GetComponent<Test>();
Load();
}
void Load()
{
for (int i = 0; i < 2; i++)
{
Debug.Log(test.itemDic[keyName]);
if (test.itemDic.ContainsKey(keyName))
{
this.GetComponent<Text>().text = test.itemDic[keyName];
}
}
}
}
and error message :,
KeyNotFoundException: The given key was not present in the dictionary. System.Collections.Generic.Dictionary`2[System.String,System.String].get_Item (System.String key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150) TestLoader.Load () (at Assets/TestLoader.cs:23) TestLoader.Start () (at Assets/TestLoader.cs:16)
You need to load your dictionary in the Awake for Test class. Then TestLoader can use it in Start which happens after. Also, the error happens because you are trying to log before you check if the dictionary contains the key. You could look into TryGetValue method for dictionary.
Answer by ShadyProductions · Feb 17, 2020 at 07:34 AM
I'm guessing your dictionary script is loaded after the other script that uses it, so it is not yet loaded. Try setting the script execution order correctly, or do not use monobehaviour to initialize it.
i will try your solution idea. i hope it will be work. thanks
Your answer
Follow this Question
Related Questions
Can't get OnTriggerEnter2D or OnCollisionEnter2D to work 1 Answer
Why is this happening? 0 Answers
Unity 5 Multiple Screen Space Overlay Canvas issue 0 Answers
Collision Box problem 1 Answer
Different time in same animation for duplicated objects 0 Answers