返回首页
[入门教程] Unity3D 本地数据持久化记录存储
本帖最后由 UnityAsk 于 2019-8-13 23:08 编辑

下面介绍几种 Unity本地记录存储的实现方式。

第一种 Unity自身提供的 PlayerPrefs
//保存数据

[mw_shl_code=csharp,true]PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)[/mw_shl_code]
//读取数据

[mw_shl_code=csharp,true]mName=PlayerPrefs.GetString("Name","DefaultValue");
mAge=PlayerPrefs.GetInt("Age",0);
mGrade=PlayerPrefs.GetFloat("Grade",0F);[/mw_shl_code]
[mw_shl_code=csharp,true]//清除所有记录

PlayerPrefs.DeleteAll();
//删除其中某一条记录

PlayerPrefs.DeleteKey("Age");
//将记录写入磁盘

PlayerPrefs.Save()[/mw_shl_code]
第二种 BinaryFormatter 二进制序列化
假设有一个Player类

[mw_shl_code=csharp,true][System. Serializable]
public class Player
{
      public int health;
      public int  power;
      public Vector3 position;
}[/mw_shl_code]
由于BinaryFormatter序列化不支持Unity的Vector3类型,所以我们需要做一下包装。

[mw_shl_code=csharp,true]public class PlayerData{

    public int level;
    public int health;
    public float[] position;

    public PlayerData(Player player)
    {
        this.level = player.level;
        this.health = player.health;
        this.position = new float[3];
        this.position[0] = player.transform.position.x;
        this.position[1] = player.transform.position.y;
        this.position[2] = player.transform.position.z;
    }
}[/mw_shl_code]
我们对PlayerData进行保存和读取。读取出来的PlayerData可以赋给Player。

[mw_shl_code=csharp,true]public static class SaveSystem{
       //保存数据
    public static void SavePlayer(Player player)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath+"/player.fun";
        FileStream stream = new FileStream(path,FileMode.Create);
        PlayerData data = new PlayerData(player);
        formatter.Serialize(stream,data);
        stream.Close();
    }

     //读取数据
    public static PlayerData LoadPlayer()
    {
        string path = Application.persistentDataPath+"/player.fun";
        if(File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path,FileMode.Open);
            PlayerData data = formatter.Deserialize(stream) as PlayerData;
            stream.Close();
            return data;
        }else{
            Debug.LogError("Save file not found in  "+path);
            return null;
        }
    }
}[/mw_shl_code]
第三种 保存为json格式的文本文件
使用 Unity 自身API JsonUtility。

保存数据

   [mw_shl_code=csharp,true] public static void SavePlayerJson(Player player)
    {
        string path = Application.persistentDataPath+"/player.json";
        var content = JsonUtility.ToJson(player,true);
        File.WriteAllText(path,content);
    }[/mw_shl_code]
读取数据

[mw_shl_code=csharp,true]   public static PlayerData LoadPlayerJson()
    {
        string path = Application.persistentDataPath+"/player.json";
        if(File.Exists(path)){
            var content = File.ReadAllText(path);
            var playerData = JsonUtility.FromJson<PlayerData>(content);
            return playerData;
        }else{
            Debug.LogError("Save file not found in  "+path);
            return null;
        }
    }[/mw_shl_code]
第四种 XmlSerializer进行串行化
假如有类

[mw_shl_code=csharp,true]public class Entity
{
    public Entity()
    {
    }
    public Entity(string c, string f)
    {
      name = c;
      school = f;
    }
    public string name;
    public string school;
}[/mw_shl_code]
读取数据

[mw_shl_code=csharp,true]List<Entity> entityList=null;
XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
using (StreamReader sr = new StreamReader(configPath))
{
   entityList = xs.Deserialize(sr) as List<Entity>;
}[/mw_shl_code]
保存数据

[mw_shl_code=csharp,true]List<Entity> entityList=null;
XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));
using (StreamWriter sw = File.CreateText(configPath))
{
  xs.Serialize(sw, entityList);
}[/mw_shl_code]
对应的xml文件为:

[mw_shl_code=csharp,true]<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEntity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Entity>
  <Name>Alice</Name>
  <School>SJTU</School>
</Entity>
<Entity>
  <Name>Cici</Name>
  <School>CSU</School>
</Entity>
<Entity>
  <Name>Zero</Name>
  <School>HIT</School>
</Entity>
</ArrayOfEntity>[/mw_shl_code]






66666666666666666666666666
  • 板凳 f123
  • 5 天前
赞66666666
学习了!
返回首页