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

本文介绍Unity游戏中使用PlayerPrefs和序列化方法保存玩家数据的技术细节,包括数据类型、存储过程及跨平台路径设置。

游戏中常常需要保存玩家的数据,如果是简单的数据,unity已经提供一种非常方便的数据存储的方式:

PlayerPrefs:数据持久化方案

采用键值对的方式对数据进行存储,可以存储Int,Float,String类型的数据

例如:PlayerPrefs.SetInt("Index",1);          PlayerPrefs.SetFloat("Height",10.2f)       PlayerPrefs.SetString("Name","Tom")

获取数据PlayerPrefs.GetInt("Index")

这是unity提供用来存储简单的数据,如果需要存储复杂和大量数据的话,通常会选择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";
        }
    }
}

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值