本文共 2377 字,大约阅读时间需要 7 分钟。
01.C#转成xmlusing System;using System.Collections;using System.Collections.Generic;using System.Xml.Serialization;using UnityEngine;[Serializable]public class Player{ [XmlAttribute] public int Id { get; set; } [XmlAttribute] public string Name { get; set; } [XmlArray] public List List { get; set; } }
void InitXml() { Player player=new Player(); player.Id = 100; player.Name = "得到"; player.List=new List (){ 1,2,3}; FileStream stream=new FileStream(Application.dataPath+"/Players",FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite); StreamWriter streamWriter=new StreamWriter(stream,Encoding.UTF8); XmlSerializer xml=new XmlSerializer(typeof(Player)); xml.Serialize(stream,player); streamWriter.Close(); stream.Close(); }}
结果
1 2 3
02.xml解析
FileStream stream = new FileStream(Application.dataPath + "/Players.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); XmlSerializer xml = new XmlSerializer(typeof(Player)); Player player = (Player)xml.Deserialize(stream); stream.Close();
[Serializable]public class Monster{ public int Id { get; set; } public string Name { get; set; } public List List { get; set; }}
03.类转成二进制
void Bin() { Monster monster=new Monster(); monster.Id = 123; monster.Name = "弟弟"; monster.List=new List (){ 2,6,90}; FileStream fileStream=new FileStream(Application.dataPath+"/monster.bytes",FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite); BinaryFormatter bf=new BinaryFormatter(); bf.Serialize(fileStream,monster); fileStream.Close(); }
04.二进制转成类
void BinF() { TextAsset textAsset=UnityEditor.AssetDatabase.LoadAssetAtPath("Assets"+ "/monster.bytes"); MemoryStream memory=new MemoryStream(textAsset.bytes); BinaryFormatter bf = new BinaryFormatter(); Monster monster=(Monster)bf.Deserialize(memory); Debug.Log(monster.Name); }
05.assets序列化
[CreateAssetMenu(fileName ="text",menuName ="creatText",order = 0)]public class AssectSer : ScriptableObject{ public int id; public int[] sum;}
转载地址:http://xfrxo.baihongyu.com/