Home > OS >  Last Dictionary<Key Value> is not added to the List from a CSV import in Unity
Last Dictionary<Key Value> is not added to the List from a CSV import in Unity

Time:07-11

So i try to read a CSV script modular in Unity. Everything works nearly fine only the last Key Value is not added to the list although it exists in the Dictionary.

    string[] data = fileString.Split(new string[] {";", "\n"}, StringSplitOptions.None);
    Debug.Log(data.Length);
    int rows = data.Length / columns - 1;

    List<string> kartenvariablen = new List<string>();
    for (int i = 0; i<= columns; i  )
    {
         kartenvariablen.Add(data[i]);                
    }
    Debug.Log(kartenvariablen.Count);
    Debug.Log(kartenvariablen[9]);

    List<Dictionary<string, string>>  allCards = new List<Dictionary<string, string>>();
    for(int i=0; i< rows; i  )       
    { 
        Dictionary<string, string> singleCard = new Dictionary<string, string>();

        for(int n= 0; n <= columns; n  )
        {
            singleCard.Add(kartenvariablen[n], data[columns 1 n (i*(columns 1))]);     
        }
        foreach (KeyValuePair<string, string> s in singleCard)
        {
            Debug.Log(s);   //here it returns Alignment TopLeft
        }
        allCards.Add(singleCard);
       
    }
    Debug.Log(allCards[2]["PrefabName"]); //returns test3 
    Debug.Log(allCards[2]["Alignment"]); //returns KeyNotFoundException: The given key 'Alignment' was not present in the dictionary.

System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <6073cf49ed704e958b8a66d540dea948>:0) CSVTemplateReader.ReadCSV () (at Assets/Scripts/CSVTemplateReader.cs:106) CSVTemplateReader.Start () (at Assets/Scripts/CSVTemplateReader.cs:19)enter image description here

CodePudding user response:

Probably either:

int rows = data.Length / columns;

or

for(int i=0; i <= rows; i  )      

is required in your case

CodePudding user response:

Ok I fixed the code. The logic behind was completely fine. The problem was it didnt saved the Alignment Key with "Alignment", but he saved it as "Alignment\r". So i refactored the code at the beginning with: string[] data = fileString.Split(new string[] {";", "\r\n"}, StringSplitOptions.None); And now it works completely fine. Thanks for all the answers and the help!

  • Related