Вывод c XML

Форум для самых маленьких, а так же тех, кому недосуг читать справку самостоятельно.

Вывод c XML

Сообщение DesQuik 17 фев 2019, 02:14

Добрый вечер. Есть скрипт создания xml файла в инспекторе юнити, выглядит он так:
Синтаксис:
Используется csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;

public class DialogueGenerator : MonoBehaviour
{
    public string fileName = "Example";
    public string folder = "Russian";
    public DialogueNode[] node;

    public void GenerateXml()
    {
        string path = Application.dataPath + "/GameDialogues" + "/" + folder + "/" + fileName + ".xml";

        XmlNode userNode;
        XmlElement element;
       
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode rootNode = xmlDoc.CreateElement("Dialogue");
        XmlAttribute attribute = xmlDoc.CreateAttribute("FileName");
        attribute.Value = fileName;
        rootNode.Attributes.Append(attribute);
        xmlDoc.AppendChild(rootNode);

        for (int j = 0; j < node.Length; j++)
        {
            userNode = xmlDoc.CreateElement("Node");
            attribute = xmlDoc.CreateAttribute("ID");
            attribute.Value = j.ToString();
            userNode.Attributes.Append(attribute);
            attribute = xmlDoc.CreateAttribute("Name");
            attribute.Value = node[j].name;
            userNode.Attributes.Append(attribute);
            attribute = xmlDoc.CreateAttribute("CharText");
            attribute.Value = node[j].charText;
            userNode.Attributes.Append(attribute);

            for (int i = 0; i < node[j].playerAnswer.Length; i++)
            {
                element = xmlDoc.CreateElement("Answer");
                element.SetAttribute("Text", node[j].playerAnswer[i].answerText);
                if(node[j].playerAnswer[i].toNode > 0) element.SetAttribute("ToNode", node[j].playerAnswer[i].toNode.ToString());
                if(node[j].playerAnswer[i].exit) element.SetAttribute("Exit", node[j].playerAnswer[i].exit.ToString());
                userNode.AppendChild(element);  
            }

            rootNode.AppendChild(userNode);
        }
       
        xmlDoc.Save(path);
        Debug.Log(this + " Создан XML файл диалога [ " + fileName + " ] по адресу: " + path);
    }
}

[System.Serializable]
public class DialogueNode
{
    public string name;
   
    [TextArea(3,10)]
    public string charText;
   
    public PlayerAnswer[] playerAnswer;
}

[System.Serializable]
public class PlayerAnswer
{
    public string answerText;
    public int toNode;
    public bool exit;
}
 


Результат:
Скрытый текст:
Изображение

Затем, я его читаю следующим скриптом:
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml.Linq;

[XmlRoot("Dialogue")]
public class DialogueManager
{
    [XmlElement("Node")]
    public Node[] nodes;

    public static DialogueManager Load(TextAsset _xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(DialogueManager));
        StringReader reader = new StringReader(_xml.text);
        DialogueManager dialogue = serializer.Deserialize(reader) as DialogueManager;
        return dialogue;
    }
}

[System.Serializable]
public class Node
{
    [XmlAttribute("Name")] public string nameText;
    [XmlAttribute("CharText")] public string charText;
   
    [XmlElement("Answer")]
    public Answer[] answers;
}

[System.Serializable]
public class Answer
{
    [XmlAttribute("Text")] public string textAnswer;
    [XmlAttribute("ToNode")] public int toNode;
    [XmlAttribute("Exit")] public string exit;

}


И идет вывод в консоль:
Синтаксис:
Используется csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DialogueTrigger : MonoBehaviour
{
    public TextAsset textFile;
   
    void Start()
    {
        DialogueManager dialogue = DialogueManager.Load(textFile);
        foreach (Node nd in dialogue.nodes)
        {
            Debug.Log(nd.nameText);
            Debug.Log(nd.charText);
            foreach (Answer an in nd.answers)
            {
                Debug.Log(an.textAnswer);
            }
        }
    }
}
 


Все вроде бы хорошо, вот только юнити пишет ошибку:
Скрытый текст:
Изображение

Прошу, помогите, пол дня убил на это, но так и не понял в чем проблема.
DesQuik
UNец
 
Сообщения: 1
Зарегистрирован: 17 фев 2019, 02:07

Re: Вывод c XML

Сообщение seaman 17 фев 2019, 20:33

Во втором узле диалога нет Answer
seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Google [Bot], Yandex [Bot] и гости: 25