繁体   English   中英

将字典保存到文本文件(C#)

[英]Save dictionary to text file (C#)

我想将字典保存到Unity3D中的文本文件中(使用C#)。 字典包含GameObjects作为键,对应于Vector2的列表。

这是我的代码:

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());        
        }
    }
}

生成示例文件:

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]

我的问题是该文件需要包含Vector2列表中的实际项目,而不是列表本身:

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

我希望上面的行看起来像这样:

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

我将如何做到这一点?

我以前没有使用过Unity,因此如果我误解了,我们深表歉意。 如果Vector2是您创建的自定义类,则可以覆盖默认的ToString()方法,以便它吐出所需的任何字符串。 另外,您需要访问试图从字典中的值中写出的任何属性。 例如(假设Foo是您的财产)。

file.WriteLine (entity.ToString() + ": " + levelStruct[entity].Foo.ToString());

您可以创建特定类型的变量并获取所需的属性

   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);

            }
        }
    }

我认为您应该使用序列化和反序列化来保存和恢复对象,因为在使用ToString()函数时,大多数情况下仅返回对象的名称。 我建议您用谷歌搜索,但是有一些资源:

http://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part

https://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx

您正在编写对象。 在对象上调用ToString()时,将获得对象类型的名称。 相反,您需要执行以下两项操作之一:

#1:如果您确实想使用CSV编写代码,则建议:

  Object.Property.ToString();

对于GameObject,您可能需要使用反射来做到这一点

 using System.Reflection;
 foreach(PropertyInfo p in typeof(UnityEngine.GameObject).GHetProperties()){
     Console.WriteLine(p.Name+","+p.GetType().ToString());
 }
 //repeat as necessary with fields and methods and ... as needed using System.Reflection

第二项是向量列表-同样。 为此,您将使用

 foreach(UnityEngine.Vector2 vect in levelStruct[entity])){
    //write ToString();
  }

#2:了解如何将对象序列化为XML或Json并保存,然后以这种方式保存: https : //www.google.com/search? q=c-sharp+how+to+serialize+objects+into+json&ie =& oe =

祝您好运-如果您遇到某些特定问题,请问问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM