栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

unity中的数据持久化(PlayerPrefs 使用二进制、XML、JSON来存储读取))

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

unity中的数据持久化(PlayerPrefs 使用二进制、XML、JSON来存储读取))

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

数据持久化 前言

提示:在使用unity制作游戏时,经常需要对数据进行存储与读取(例如:角色的属性) 我们刚开始的时候接触的应该是unity提供的PlayerPrefs(通过过key-value的形式写入、读取、更新),在这里记录一下如何使用二进制、XML、JSON来实现:


一、PlayerPrefs

PlayerPrefs 是unity的内置的方法,用来储存、读取一些数据(计分板、排名)
使用Set来保存数据(长用于保存的类型:int float string bool)
PlayerPrefs.SetInt(key,value);
PlayerPrefs.SetFloat();
Playerprefs.SetString();
用0、1来实现bool值的存储

	例如:   
					PlayerPrefs.SetString(“Name”,mName);
					PlayerPrefs.SetInt(“Age”,mAge);
					PlayerPrefs.SetFloat(“Grade”,mGrade);
					PlayerPrefs.SetInt(“isTrue”,1);    //标记0、1做bool值

数据的读取(常使用Get方法)

	例如:
	String mName=PlayerPrefs.GetString(“Name”);
	Int   mAge=PlayerPrefs.GetInt(“Age”);
	Float mGrade=PlayerPrefs.GetFloat(“Grade”);

	注意:Unity中值是通过键名来读取的,当值不存在时,返回默认值。
二、二进制 二进制
		序列化:	通过将Object (对象,脚本,数据)转化为字节流写入二进制文件
		反序列化: 将二进制文件解析为object(对象,脚本,数据)

代码如下:

using System.IO;  
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine.UI;
using System;
//下面为部分代码(将学校、学院、班级、姓名存储,通过UI显示)
//序列化
public void Save()
    {
        BinaryFormatter bf = new BinaryFormatter();   //    定义一个二进制流

        FileStream file = File.Create(Application.dataPath  + "/StudentInfo.dat");   // 自定义一个文件流
		//注意:存储文件 在Unity中一定是使用各平台都可读可写可找到的路		 径
        //  1.Resources 可读 不可写 打包后找不到  
        //  2.Application.streamingAssetsPath 可读 PC端可写 找得到  
        // 3.Application.dataPath 打包后找不到  
        // 4.Application.persistentDataPath 可读可写找得到   
		//推荐使用Application.persistentDataPath
		
        StudentData data = new StudentData();  //实例化一个PlayerData类的对象
        // 此处获取UI中的数据
        data.SchoolName = Schoolfield.text;
        data.peofessionName = Professionfield.text;
        data.ClassName = Classfield.text;
        data.Name = Namefield.text;
        
        bf.Serialize(file, data);  //将data序列化为file文件(即上述定义的StudentInfo.dat)存储
        file.Close();  //关闭流操作


    } 

//反序列化
public void Load()
    {
        if(File.Exists(Application.dataPath+ "/StudentInfo.dat"))//首先    确定有存储信息
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.dataPath+"/StudentInfo.dat", FileMode.Open);

            StudentData data = new StudentData();  //实例化信息类

              data =  bf.Deserialize(file) as StudentData;   file文件化为data数据
            file.Close(); //关闭流操作
            //将文件流的数据转换为object类型
            Schoolfield.text=data.SchoolName ;
            Professionfield.text=data.peofessionName;
            Classfield.text=data.ClassName;
            Namefield.text=data.Name;
            
        }
		else{
			DeBug.Log("加载数据错误");
		}

    }


//***************************************
    //存储的信息有学校,学院,班级,姓名
[Serializable]  //可序列化标志(未将数据序列化的话,在序列化数据时会报错)
class StudentData
{
    public string SchoolName;
    public string peofessionName;
    public string ClassName;
    public string Name;
   
}

二进制方法(简单,但可读性差):序列化:新建或打开一个二进制文件,通过二进制格式器将对象写入该二进制文件
反序列化:打开反序列化的二进制文件,通过二进制格式器将文件解析成对象

创建出来的二进制文件如上(乱码,看不懂)


三、XML XML: 扩展标记语言 可以用来标记数据、定义数据类型。
  序列化与反序列化的方式与二进制方法十分相似
 C# 读取XML文件的方法:
  1. XmlDocument(把数据加载到内存中,比较耗内存,方便读取)
  2. XmlTextReader(以流形式加载,内存占用更少,单向只读,使用不方便)
    XML文件格式:

    代码如下:
using System;
using System.IO;
using UnityEngine.UI;
using System.Xml;

public class PresonInfoSer : MonoBehaviour {

    public InputField NameText;
    public InputField HeightText;
    public InputField WeightText;
    public InputField CharText;
    public Button SaveBtn;
    public Button LoadBtn;
    private string path;

    private Dictionary DataDic = new Dictionary();


    void Awake()
    {
        ReadXml();  //加载数据
        
    }
	
    public void Save()
    {
    	//将数据存储进字典
        DataDic.Add("Name", NameText.text);
        DataDic.Add("Height",HeightText.text.ToString());
        DataDic.Add("Weight", WeightText.text.ToString());
        DataDic.Add("Charactor", CharText.text);
			
			//文件存储在设备的公用目录下  使用Debug可以看到路径
        path = Application.persistentDataPath + "/PresonInfoSer.xml";
        Debug.Log("文件被存储在"+path);
        XmlDocument xml = new XmlDocument();  //创建XML文件

        XmlDeclaration xmlDec = xml.CreateXmlDeclaration("1.0", "UTF-8", null);			//添加版本 序列化
        xml.AppendChild(xmlDec);  //添加给xml文本对象
			

        XmlElement rootNode = xml.CreateElement("Root");  //创建根节点
        xml.AppendChild(rootNode);  //添加进xml文本

        foreach(KeyValuePair pair in DataDic)  //遍历字典
        {
            XmlElement element = xml.CreateElement(pair.Key);  //创建子节点
            element.InnerText = pair.Value;  //子节点的值
            rootNode.AppendChild(element);  //添加到根节点下面
        }

        xml.Save(path);   //编写完别忘记保存
    }
    public void ReadXml()   //读取xml文件
    {
        path = Application.persistentDataPath + "/PresonInfoSer.xml";
       // Debug.Log("文件被存储在"+path);
        XmlReader reader = XmlReader.Create(path);  //创建读出流操作文件

        while (reader.Read())    //循环读取各行内容,直到文档结束
        {
        	//IsStartElement用来判断是否存在当前元素
            if (reader.IsStartElement("Name"))
            {
            	//读取当前节点并返回String类型的对象给text
                NameText.text = reader.ReadElementContentAsString();
            }
            if (reader.IsStartElement("Height"))
            {
                HeightText.text = reader.ReadElementContentAsString();
            }
            if (reader.IsStartElement("Weight"))
            {
                WeightText.text = reader.ReadElementContentAsString();
            }
            if (reader.IsStartElement("Charactor"))
            {
                CharText.text = reader.ReadElementContentAsString();
            }
        }

        reader.Close();  //关闭流文件

    }
}
[Serializable]
class PeopleInfo{

    public string Name;
    public float Height;
    public float Weight;
    public string Charactor;

}


四、JSON 通过JSON来读写(利用插件LitJson) # JSON官方介绍:

JSON 是轻量级的文本数据交换格式
JSON 独立于语言 * JSON 具有自我描述性,更易理解 * JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。

JSON(数据格式简单,易于读写,但是不够直观,可读性比XML差):是一种语言无关的发送和接受数据的常用格式。可以使用它来跨平台的传输数据。

Json是目前的使用较为频繁、方便的,推荐使用

Json文件(字符串):

将LitJson.dill引入项目中:

没有的小伙伴点击下面的链接(免费下载):

LitJson下载地址

存储和加载Json文件:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using LitJson;

public class PresonJSON : MonoBehaviour {

    public InputField NameText;
    public InputField HeightText;
    public InputField WeightText;
    public InputField CharText;
    public Button SaveBtn;
    public Button LoadBtn;
    private string path;
    personList list = new personList();
    
    void Awake()
    {
        Load();
    }
    // Use this for initialization
    void Start () {
		//print(Application.persistentDataPath + "/" + "personJsonInfo.json");
	}
	
	// Update is called once per frame
	void Update () {
		
	}

     void WriteJSON(personInfo_JSON person,string path)
    {
        if (!File.Exists(path))
        {

            
            list.data.Add("Name",person.Name);
            list.data.Add("Height",person.Height.ToString());
            list.data.Add("Weight",person.Weight.ToString());
            list.data.Add("Charactor", person.Charactor);
        }
        else
        {
            list.data["Name"] = person.Name;
            list.data["Height"] = person.Height.ToString();
            list.data["Weight"] = person.Weight.ToString();
            list.data["Charactor"] = person.Charactor;
        }
			//将数据转化为json类型的字符串
        string jsonStr = JsonMapper.ToJson(list.data);
			//将字符串写入(如果使用FileStream流,记得关闭流)
        File.WriteAllText(path, jsonStr);

    }
    public void Save()
    {
        personInfo_JSON js = new personInfo_JSON();
        js.Name = NameText.text;
        js.Height = float.Parse(HeightText.text);
        js.Weight = float.Parse(WeightText.text);
        js.Charactor = CharText.text;
        //调用WriteJSON方法保存数据
        path = Application.persistentDataPath + "/" + "personJsonInfo.json";
        WriteJSON(js, path);

    }
    public void Load()
    {
        path = Application.persistentDataPath + "/" + "personJsonInfo.json";
        if (File.Exists(path))
        {
        		//读取字符串
            string Reader = File.ReadAllText(path);
            //将
            JsonData jsonData = JsonMapper.ToObject(Reader);
            NameText.text = jsonData["Name"].ToString();
            HeightText.text = jsonData["Height"].ToString();
            WeightText.text = jsonData["Weight"].ToString();
            CharText.text = jsonData["Charactor"].ToString();

        }
        else
        {
            Debug.Log("读取数据错误");
        }
    }
}

public class personInfo_JSON{

    public string Name;
    public float Height;
    public float Weight;
    public string Charactor;
}
public class personList
{
    public Dictionary data = new Dictionary(); 
}


总结

以上就是本人理解的存储读取数据内容的基本方法,在此总结一下,有错误请指出,感谢。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/898966.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号