做游戏需要时刻保存游戏的进度,游戏数据全部保存在本地是不现实的,这样每次重新开始游戏,数据会被清空,所以需要xml文件
PlayerPrefs是unity自带的数据结构,在UnityEngine命名空间下,可以对整数,浮点数,字符串3种类型的数据进行操作
PlayerPrefs使用键值配对规则
PlayerPrefs.SetInt(“Number”, num);//存储,第一个参数是键,第二个是值
int num = PlayerPrefs.GetInt(“Number”);//读取
float PI = 3.14f;
PlayerPrefs.SetFloat(“PI”, PI);
PI = PlayerPrefs.GetFloat(“PI”);
String str = “neworigin”;
PlayerPrefs.SetString(“Str”, str);
Str5 =PlayerPrefs.GetFloat(“Str”);
对xml文件进行增删改查操作
核心代码:
using UnityEngine;
using System.Collections;
using System.Xml;
public class heng : MonoBehaviour {
public string xmlFileName = "/test.xml";//文件名
public string xmlFilePath = string.Empty;//路径
public XmlNode _root;//根
public XmlNode node;//节点
public XmlNode child node;//子节点
public XmlDocument _doc;//文件的内容
void Awake(){
xmlFilePath = Application.streamingAssetsPath + xmlFileName;//
}
void Start () {
_doc = new XmlDocument ();
_doc.Load (xmlFilePath);//根据文件路径加载文件
_root = _doc.SelectSingleNode ("plist");//根节点
XmlElement element = _doc.CreateElement ("mystring");//创建
element.InnerText = "dsfsdfgd";
//add ("key",element);//增加
//remove("array","string3");//移除
//find ("string5");//查找
replace ("array","string5",element);//替换
}
// Update is called once per frame
void Update () {
}
//加载文件
void load(XmlNode _root,string parentelement,string childelement = ""){
foreach(XmlNode element in _root){
if(element.Name.Equals(parentelement)){
node = element;
}
if(element.Name.Equals(childelement)){
childnode = element;
}
load(element,parentelement,childelement);
}
}
//添加
void add(string parentelement,XmlElement newelement){
load (_root,parentelement);
if (node != null) {
Debug.Log("SDSDA");
node.AppendChild (newelement);
_doc.Save(xmlFilePath);
}
}
//移除
void remove(string parentname,string childname){
load (_root,parentname,childname);
if(node!=null&&childnode!=null){
Debug.Log("remove");
node.RemoveChild(childnode);
_doc.Save(xmlFilePath);
}
}
//查找
void find(string nodename){
load (_root,nodename);
if (node!=null) {
Debug.Log("find");
Debug.Log(node.InnerText);
}
}
//替换
void replace(string parentname,string oldchildname,XmlElement newchilename){
load (_root,parentname,oldchildname);
if(node!=null&&childnode!=null){
Debug.Log("replace");
node.ReplaceChild(newchilename,childnode);
_doc.Save(xmlFilePath);
}
}
}
![这里写图片描述](http://img.blog.csdn.net/20160806162350014)
foreach (XmlElement childNode in _root) {
if(childNode.Name.Equals("dict")){
foreach(XmlElement grandSon in childNode){
//grandSon.AppendChild(element);
if(grandSon.Name.Equals("array"))
//grandSon.AppendChild(element);//add
//grandSon.RemoveChild(grandSon,grandSon.LastChild);
//grandSon.RemoveChild(element,grandSon.LastChild);
{
foreach(XmlElement maternal in grandSon){
Debug.Log(maternal.InnerText);
}
}
}
}
}
“`