Bonbin Bonbin - 2 months ago 20
C# Question

Save dictionary to text file (C#)

I want to save a dictionary to a text file in Unity3D (using C#). The dictionary contains GameObjects as keys which corresponds to lists of Vector2's.

This is my code:

public void SaveLevel(string LevelName)
{
using (StreamWriter file = new StreamWriter (LevelName+".txt"))
{
foreach (GameObject entity in levelStruct.Keys)
{
file.WriteLine (entity.ToString () + ": " + levelStruct[entity].ToString());
}
}
}


Which produces the example file:

wall (UnityEngine.GameObject): System.Collections.Generic.List`1[UnityEngine.Vector2]
rat (UnityEngine.GameObject): System.Collections.Generic.List`1[UnityEngine.Vector2]
dwarf (UnityEngine.GameObject): System.Collections.Generic.List`1[UnityEngine.Vector2]
floor (UnityEngine.GameObject): System.Collections.Generic.List`1[UnityEngine.Vector2]


My issue is that the file needs to contain the actual items in the Vector2 list, not the list itself:

System.Collections.Generic.List1[UnityEngine.Vector2]


I want the above line to look something like this:

System.Collections.Generic.List1[(0,2),(3,1),(4,3)]


How would i accomplish this?

Answer

you can create a varaible of the specific type and get the properties you need

   public void SaveLevel(string LevelName) 
    {
    string res;
        using (StreamWriter file = new StreamWriter (LevelName+".txt"))
        {
            foreach (GameObject entity in levelStruct.Keys)
            { 
                foreach(Vector2 v in levelStruct[entity])){
                      res = " "+"("+v.x+"."+v.y+")";
             }
          file.WriteLine (entity.ToString () + ": " + res);

            }
        }
    }