【问题标题】:Problem while saving gameobjects' data in XML file在 XML 文件中保存游戏对象的数据时出现问题
【发布时间】:2020-12-11 18:58:56
【问题描述】:

我试图将游戏对象的数据保存在 XML 文件中,但在 XML 文件中,我只从列表中获取最后一个值,而不是两个不同的值。我已经在不同的两个不同游戏对象下实例化了两个工具提示,并且我将这些实例化的工具提示存储在列表中。当我打印工具提示的文本时,我得到了两个不同的值,但是当我尝试将这两个值保存在 XML 文件中时,我在 XML 文件中得到了最后一个实例化工具提示的文本值两次。

型号:

Handle 和 Key 游戏对象下带有实例化工具提示的模型(用红线标记):

场景:

如果我在两个不同的对象上用值“text1”和“text2”实例化了两个工具提示,那么我想将“text1”和“text2”值存储在 XML 文件中。

下面是代码。

 public ItemEntry newItem = new ItemEntry();
 public ItemDatabase itemDB;
 ObjectSpawnManager ObjectSpawnManager;
 
 private void Start()
 {
     ObjectSpawnManager = GetComponent<ObjectSpawnManager>();
 }
 public void SaveFeedback(GameObject parentGameObject)
 {
     foreach (GameObject go in ObjectSpawnManager.iconTooltipList)
     {
         Debug.Log(go.GetComponentInChildren<TMPro.TextMeshPro>().text);
         newItem.toolTipText = go.GetComponentInChildren<TMPro.TextMeshPro>().text;
         itemDB.list.Add(newItem);
     }
     XmlSerializer serializer = new XmlSerializer(typeof(ItemDatabase));
     FileStream stream = new FileStream(Application.dataPath + "/Feedback Solution/feedback_data.xml", FileMode.Create);
     serializer.Serialize(stream, itemDB);
     stream.Close();
 }
 public class ItemEntry
 {
     public string toolTipText;
 }
 
 public class ItemDatabase
 {
     public List<ItemEntry> list = new List<ItemEntry>();
 }

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您能告诉我们您是如何添加条目的吗?并显示相应对象的层次结构。两次使用GetComponentInChildren 也是非常多余的......你应该存储字符串并重新使用它
  • @derHugo..非常感谢您的帮助!我试图把我的 ItemEntry newItem = new ItemEntry();在 forloop 开始时,它起作用了。但我仍然想知道我的代码中是否有什么可以重构的。正如您建议的 GetComponentInChildren 冗余...]

标签: list unity3d xml-serialization augmented-reality


【解决方案1】:

我通过在 for 循环下初始化 public ItemEntry newItem = new ItemEntry(); 来解决这个问题,它对我有用。

【讨论】:

    最近更新 更多