Unity中将类对象保存到XML中

该代码包含两个功能

(1)在Unity中在本地创建XML文件,将类对象转换为字符串保存到XML文件中

(2)将存入的XML文件读取出来转换为相应的 类对象


using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;

public class AAA
{
    public int num;
    public BBB bbb;
    public AAA()
    {
        num = 0;
        bbb = new BBB();
    }
}

public class BBB
{
    string name;
    public BBB()
    {
        name = "aaaaa";
    }
}

// 将类对象保存为 XML, 将XML读取为类对象
public class WriteReadTxt : MonoBehaviour {

    string path = "";

    void Start()
    {
        path = Application.dataPath + "StreamingAssets/AAA/1.xml";
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))  //  保存对象
        {
            AAA aaa = new AAA();
            CreateWriteXML<AAA>( path, aaa, true);  // 将类直接保存为 XML文件
        }

        if (Input.GetKeyDown(KeyCode.D))   // 读取对象
        {
            AAA aaa = new AAA();
            aaa = ReadXmlFile<AAA>(path);  // 将读取的XML文件转换为类
        }
    }

    // 创建写入文件 , 参数1 文件路径, 参数 2 写入信息, 参数3 是否删除之前的重新创建
    public void CreateWriteFile(string path, string info, bool isRelace) 
    {
        StreamWriter sw;
        FileInfo t = new FileInfo( path); //获取路径下文件信息

		if (t.Exists && isRelace)  //如果存在则删除
		{
			File.Delete(path);
		}
		
        if (!t.Exists)        //如果文件不存在则创建一个
        {
			sw = t.CreateText();
        }
        else 
        {
            sw = t.AppendText();
        }
        sw.WriteLine( info);   //写入信息
        sw.Close();
        sw.Dispose();
    }
    //读取文件, 参数1 文件路径, 参数2 保存路径的集合
    public List<string> ReadTxtFile(string path, List<string> saveList) 
    {
        FileInfo info = new FileInfo(path);  //获取路径下文件信息
        if (!info.Exists)   //如果不存在返回
        {
			Debug.Log("!exist    " + path);
            return saveList;
        }

        StreamReader sr = null;
        sr = File.OpenText(path);  //存在则打开文件

        string line;
        while ((line = sr.ReadLine()) != null)  // 一行一行读取文件
        {
            saveList.Add(line);    //向保存文件集合添加 路径字符串
        }

        sr.Close();
        sr.Dispose();

        return saveList;
    }
    // 参数1 路径,参数2 需要保存的类,参数3 是否需要替换
    public void CreateWriteXML<T>( string path, T t, bool isRelace) 
    {
        string data = SerializeObject<T>(t);  // 将类对象转换为 字符串
        CreateWriteFile(path, data, isRelace);
    }

    public T ReadXmlFile<T>(string path)
    {
        List<string> dataList = new List<string>();
        string data = "";
        dataList = ReadTxtFile(path, dataList);

        foreach (string str in dataList)
        {
            data += str;
        }

        T t = (T)DeserializeObject<T>(data);

        return t;
    }

    private string UTF8ByteArrayToString(byte[] characters)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        string constructedString = encoding.GetString(characters);
        return (constructedString);
    }

    private byte[] StringToUTF8ByteArray(string pXmlString)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] byteArray = encoding.GetBytes(pXmlString);
        return byteArray;
    }
    // 保存xml 前先将 类对象转换为 字符串
    private string SerializeObject<T>(object pObject) 
    {
        string XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        //XmlSerializer xs = new XmlSerializer(typeof(UserData));
        XmlSerializer xs = new XmlSerializer(typeof(T));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        xs.Serialize(xmlTextWriter, pObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }
    // 将读取的xml字符串转换为 类对象
    private object DeserializeObject<T>(string pXmlizedString)  
    {
        //XmlSerializer xs = new XmlSerializer(typeof(UserData));
        XmlSerializer xs = new XmlSerializer(typeof(T));
        MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        return xs.Deserialize(memoryStream);
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题我可以回答。在Unity,你可以使用XmlDocument类来创建和读取XML文件。以下是一个简单的示例代码,演示如何将游戏对象的信息保存XML文件,以及如何从XML文件读取信息并重新创建游戏对象保存XML文件: ```csharp using System.Xml; using UnityEngine; public class GameObjectXmlSaver : MonoBehaviour { public void SaveGameObjectToXml(string filename, GameObject gameObject) { XmlDocument xmlDoc = new XmlDocument(); // Create the root element and add it to the document XmlElement rootElement = xmlDoc.CreateElement("GameObject"); xmlDoc.AppendChild(rootElement); // Add the object's transform information to the XML XmlElement transformElement = xmlDoc.CreateElement("Transform"); transformElement.SetAttribute("Position", gameObject.transform.position.ToString()); transformElement.SetAttribute("Rotation", gameObject.transform.rotation.ToString()); rootElement.AppendChild(transformElement); // Add any other information you want to save about the object // Save the XML to a file xmlDoc.Save(filename); } } ``` 从XML文件读取并创建游戏对象: ```csharp using System.Xml; using UnityEngine; public class GameObjectXmlLoader : MonoBehaviour { public GameObject LoadGameObjectFromXml(string filename) { XmlDocument xmlDoc = new XmlDocument(); // Load the XML file xmlDoc.Load(filename); // Find the root element XmlElement rootElement = xmlDoc.DocumentElement; // Create a new game object GameObject gameObject = new GameObject(); // Add the transform information to the game object XmlElement transformElement = rootElement.SelectSingleNode("Transform") as XmlElement; Vector3 position = Vector3.zero; Quaternion rotation = Quaternion.identity; Vector3.TryParse(transformElement.GetAttribute("Position"), out position); Quaternion.TryParse(transformElement.GetAttribute("Rotation"), out rotation); gameObject.transform.position = position; gameObject.transform.rotation = rotation; // Add any other information you saved about the object return gameObject; } } ``` 注意,这只是一个简单的示例,你可能需要根据自己的需要进行更改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值