Unity中使用序列化来保存本地游戏数据

Unity中使用序列化来保存本地游戏数据

游戏中常常会遇到需要保存玩家数据的情况,如果是简单的数据,unity已经提供一种非常方便的数据存储的方式:PlayerPrefs类。但是这样存储简单的数据还好,如果用来存复杂和大量数据的话,就比较麻烦,通常可能大家会选择Xml或者Json等,我这里介绍另外一种比较方便的保存方式:
通过序列化(Serialize)来保存玩家的数据,相比xml来说,我觉得代码更加简单。

实例:
比如现在在做一款三消游戏,游戏需要保存玩家的数据,包括音效,音乐的开关,生命值,金币数量,已经达到的关卡,和每一关获得的星星数量和分数,假设现在这些数据都要保存在本地,
通常我会先写好一个玩家类,定义好这些数据

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

//玩家每一关获得的星星和分数
[System.Serializable]
public struct PlayerLevelRecord
{
    public int starCount;///<星星数量
    public int playerScore;///<分数
}

//玩家数据类
[System.Serializable]
public class PlayerData
{ 
    //游戏设置
    public bool isMusicOn=true;///<是否打开音乐
    public bool isSoundOn=true;///<是否打开音效  

    //玩家数据
    public int life=5;///<生命
    public int reachedLevel=1;///<达到的关卡
    public List<PlayerLevelRecord> list_levelScore=new List<PlayerLevelRecord>();///<每关的星星和分数

    //构造函数
    public PlayerData()
    {
        PlayerLevelRecord record = new PlayerLevelRecord();
        record.starCount = 0;
        record.playerScore = 0;
        list_levelScore.Add(record);
    }
}

定义好简单的类和数据以后,就是保存和读取数据了

public class PlayerDataOperator : MonoBehaviour 
{
    public PlayerData playerData;///<玩家对象

    private string path;///<文件的路径

    // Use this for initialization
    void Awake () {
        //在游戏刚刚运行时,根据平台,选择好对应的路径
        SetPath();        
    }

    //读取玩家的数据
    public PlayerData LoadPlayerData()
    {
        //如果路径上有文件,就读取文件
        if (File.Exists(path))
        {
            //读取数据
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(path, FileMode.Open);
            playerData = (PlayerData)bf.Deserialize(file);
            file.Close();
        }
        //如果没有文件,就new出一个PlayerData
        else
        {
            playerData = new PlayerData();
        }

        return playerData;
    }

    //保存玩家的数据
    public void SavePlayerData()
    {  
        //保存数据      
        BinaryFormatter bf = new BinaryFormatter();
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        FileStream file = File.Create(path);      
        bf.Serialize(file, playerData);
        file.Close();       

    }

    //设置文件的路径,在手机上运行时Application.persistentDataPath这个路径才是可以读写的路径
    void SetPath()
    {
        //安卓平台
        if (Application.platform==RuntimePlatform.Android)
        {
            path = Application.persistentDataPath + "/playerData.gd";
        }
        //windows编辑器
        else if (Application.platform==RuntimePlatform.WindowsEditor)
        {
            path = Application.streamingAssetsPath + "/playerData.gd";
        }
    }
}

写了不少代码,其实真正核心的保存和读取的代码分别也就4-5行,非常简单。

特别注意,如果要保存的数据中有一些不支持Unity序列化的话,可能就无法保存了,比如Dictionary容器,二维数组等等,需要通过其他办法来解决。

如果上面有什么错误的地方,请大家大胆指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章