简单的介绍几种在unity中对数据的存储和读档的方法!
在unity中实现对游戏数据的存储和读档的方法主要有这么几种:
- 使用本地持久化类PlayerPrefs
- 使用二进制的方法序列化和反序列化(Serialize、Deserialize)
- 使用Json方法
- 使用XMl方法。
下面就通过一个简单的例子分别用这四种方法实现数据的存储和读档。
实现目标:
做一个简单的得分制,按S键得分加一,按B键血量减一。UI设计上做一个保存按钮,用于保存数据,再做一个加载按钮,用于加载上一局保存的数据到场景中。
搭建场景: 由于比较简单,就不一一赘述了,直接上图:
主要的是说一下unity中Hierarchy面板中的结构,因为担心有些朋友搞混了。
首先呢,创建一个Canvas,他下面的两个image分别是血量和得分的背景(无关紧要),CurrentBloodVolume是个Text,用来显示当前的血量,CurrentScore也是个Text,用来显示当前的得分,save是个按钮,用来保存,load也是个按钮,用来加载,GameManager是个空物体,用来挂载GameManager脚本,这个脚本里面主要写了各种方法,游戏逻辑,ScoreAndBlood也是个空物体,用来挂载ScoreAndBlood脚本,这个脚本里面写了加分和减血的代码。
脚本创建: 创建一个Date脚本,这个脚本不需要继承MonoBehaviour,因为这个脚本是用来序列化和反序列化的,需要向这个类中添加游戏需要保存的数据,最后要读档的时候也是需要从这个类中读取保存的数据。还需要一个加分和减血的类ScoreAndBlood,最后还有一个游戏主逻辑类GameManager。
我们在最开始先把几段必要的代码给出来:
加分和减血的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreAndBlood : MonoBehaviour
{
public static ScoreAndBlood _instance;
public Text currentBloodVolume;
public Text currentScore;
public int BloodVolume = 100;
public int Score = 0;
private bool isCanReduce = true;
private void Awake()
{
_instance = this;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.B) && isCanReduce)
{
BloodVolume--;
currentBloodVolume.text = BloodVolume.ToString();
if (BloodVolume < 0)
{
isCanReduce = false;
}
}
if (Input.GetKeyDown(KeyCode.S))
{
Score++;
currentScore.text = Score.ToString();
}
}
}
需要存储和读取游戏数据的脚本Date:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Date
{
public int BloodVolume;
public int Score;
}
GameManager脚本中向Date中存放数据和从Date中读取数据的方法
//创建Data对象,并向其中添加游戏需要保存的数据
private Date GetGameDate()
{
Date date = new Date();
date.BloodVolume = ScoreAndBlood._instance.BloodVolume;
date.Score = ScoreAndBlood._instance.Score;
return date;
}
//向游戏中加载Date中保存的数据的方法
private void SetGameDate( Date date)
{
ScoreAndBlood._instance.currentBloodVolume.text = date.BloodVolume.ToString();
ScoreAndBlood._instance.currentScore.text = date.Score.ToString();
}
(一)PlayerPrefs
PlayerPrefs是unity提供的一个用于本地数据持久化保存、读取的类。原理很简单,就是利用key—value的方式将数据保存到本地,跟字典类似。然后通过代码进行保存、读取、更新操作。值得注意的是此方法只能保存int型、float型,string型的数据,当然,对于bool类型的可以用0和1来代替真和假,以实现保存目的。
这是用PlayerPrefs方法实现数据存储与读档的,这俩方法写在GameManager中
//用Playerprefs方法对数据进行存储和读档
private void SaveByPlayerPrefs()
{
PlayerPrefs.SetInt("bloodVolume", ScoreAndBlood._instance.BloodVolume);
PlayerPrefs.SetInt("score", ScoreAndBlood._instance.Score);
PlayerPrefs.Save();
}
private void LoadByPlayerPrefs()
{
if (PlayerPrefs.HasKey("bloodVolume") && PlayerPrefs.HasKey("score"))
{
ScoreAndBlood._instance.currentBloodVolume.text = PlayerPrefs.GetInt("bloodVolume").ToString();
ScoreAndBlood._instance.currentScore.text = PlayerPrefs.GetInt