我正在尝试对我的 XML 文件使用
XmlSerializer.Deserialize()
。这是代码:
private void LoadSceneDialogues()
{
if (dialogueXML != null)
{
sceneDialogues = new Dictionary<int, Dialogue>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Dialogue>), new XmlRootAttribute("Dialogues"));
using (var reader = new StringReader(dialogueXML.text))
{
try
{
Debug.Log("Purely for Debugging1");
var loadedData = (List<Dialogue>)serializer.Deserialize(reader);
foreach (var data in loadedData)
{
Debug.Log($"oID: {data.oID} name: {data.characterName}");
foreach (var sentence in data.sentences)
{
Debug.Log($"sentence: {sentence}");
}
Debug.Log($"sentences count: {data.sentences.Length}");
//Debug.Log($"sentences: {data.sentences}");
sceneDialogues.Add(data.oID, data);
}
if (sceneDialogues != null)
{
Debug.Log("Purely for Debugging2");
}
}
catch (InvalidOperationException ex)
{
Debug.LogError($"Error deserializing XML: {ex.Message}");
Debug.Log($"Loaded XML data:\n{dialogueXML.text}");
}
}
}
else
{
Debug.LogError("Dialogue XML file not assigned in DialogueManager!");
}
}
这是对话课:
using UnityEngine;
[CreateAssetMenu(fileName = "NewDialogue", menuName = "Dialogue")]
public class Dialogue : ScriptableObject
{
public string characterName; // 캐릭터 이름
[TextArea(3, 20)]
public string[] sentences; // 대화 내용
public int oID = -1;
public int nextoID = -1;
public int animID = -1;
}
这是我正在使用的 XML 的一部分:
<?xml version="1.0" encoding="UTF-8"?>
<Dialogues>
<Dialogue>
<oID>0</oID>
<nextoID>-1</nextoID>
<animID>0</animID>
<characterName>a</characterName>
<sentences>
<sentence>god...</sentence>
<sentence>wtf?</sentence>
</sentences>
</Dialogue>
</Dialogues>
除了句子之外,其他工作正常。 我从这个对话对象得到的数组是空的,而其他像“oid”的数组是他们应该的。 我认为这是因为“句子”是嵌套的,但我不知道如何正确处理这个问题。
做了一些日志,发现dialog.sentences是空的,而其他的则不是。 我想修改当前代码,以便它正确处理句子。
将对话句子属性更新为元素名称为“sentence”的 XMLArrayItem:
public class Dialogue : ScriptableObject
{
public string characterName; // 캐릭터 이름
[XmlArrayItem(ElementName="sentence")]
public List<string> Sentences{ get; set; }
public int oID = -1;
public int nextoID = -1;
public int animID = -1;
}