Unity版本为5.3.2
在Unity中我们经常会遇到要保存一些数据信息,比如玩家最高分,等级,金币等等。Unity为我们提供了PlayerPrefs这样一个数据持久化本地存储的类
它的函数如下:
SetInt();保存整型数据;
GetInt();读取整形数据;
SetFloat();保存浮点型数据;
GetFlost();读取浮点型数据;
SetString();保存字符串型数据;
GetString();读取字符串型数据;
DeleteKey (key : string)删除指定数据;
DeleteAll() 删除全部键 ;
HasKey (key : string)判断数据是否存在的方法;
举个例子:
using UnityEngine;
using System.Collections;
public class Information : MonoBehaviour {
int score;
string name;
public void Save(){
PlayerPrefs.SetInt ("Score",score);
PlayerPrefs.SetString ("Name",name);
}
public void Load(){
score = PlayerPrefs.GetInt ("Score",score);
name = PlayerPrefs.GetString ("Name",name);
}
}
PlayerPrefs采用键值对的方式进行存取
Android平台:apk安装在内置flash存储器上时,PlayerPrefs的位置是\data\data\com.company.product\shared_prefs\com.company.product.xml;apk安装在内置SD卡存储器上时,PlayerPrefs的位置是/sdcard/Android/data/com.company.product\shared_prefs\com.company.product.xml;是否安装到sd卡可在PlayerSetting->Other Settings->Install Location 设置。
在Windows平台下,PlayerPrefs被存储在注册表的 HKEY_CURRENT_USER\Software[company name][product name]键下(打开“运行”输入regedit打开注册表),其中company name和product name名是在Project Setting中设置。
通过上面的介绍可以看出,PlayerPrefs可以存取一些简单的数据,但是如果我们要存取一个对象呢?这个时候就需要用到序列化和反序列化的概念了。
序列化:就是是将对象转换为容易传输的格式的过程,一般情况下转化为流文件,放入内存或者IO文件中,达到持久化的目的。
反序列化:和序列化相反,通过流文件构建对象
.Net存在几种默认序列化:二进制序列化,xml序列化,json序列化(需要下载库文件);xml和json只会序列化公共属性和字段。
这里以二进制序列化为例:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;//引入二进制构造器的命名空间
using System.IO;//引入io操作命名空间
public class GameManager : MonoBehaviour {
public float health;
public float experience;
public void Save(){
BinaryFormatter bf = new BinaryFormatter ();//实例化一个二进制构造器
FileStream file = File.Create (Application.persistentDataPath+"/playerInfo.dat");//创建保存数据的文件(Application.persistentDataPath个平台不一样,但是在ios上会被iCloud备份)
PlayerData data = new PlayerData ();//序列化的对象
data.health = health;
data.experience = experience;
bf.Serialize (file,data);//序列化
file.Close ();
}
public void Load(){
if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {//判断存在否
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath+"/playerInfo.dat",FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize (file);//反序列化
file.Close ();
health = data.health;
experience = data.experience;
}
}
}
[Serializable]//一个对象要被序列化必须加(如果不想序列化某个属性或字段就在字段或属性前加[NonSerialized])
class PlayerData{
public float health;
public float experience;
}