01.存檔實(shí)現(xiàn)方式
將需要保存的數(shù)據(jù)存儲(chǔ)在一個(gè)類中,存檔時(shí),將此類序列化為二進(jìn)制數(shù)據(jù)保存在存檔文件中。
02.創(chuàng)建存檔數(shù)據(jù)類
在腳本文件夾中添加類:Archive,該類是純數(shù)據(jù),因需要序列化,所以要在類聲明處添加[Serializable]。
03.確定需要保存的數(shù)據(jù)
- 首先是固定圖層上的方塊數(shù)據(jù);
- 然后是方塊類型:當(dāng)前方塊類型和下一個(gè)方塊類型;
- 方塊坐標(biāo),讀檔時(shí)從保存的坐標(biāo)處開(kāi)始下落方塊;
- 當(dāng)前分?jǐn)?shù)和歷史最高分;
關(guān)卡是可以根據(jù)分?jǐn)?shù)來(lái)確定的,所以不需要保存。
下面是具體成員:
// 固定圖層數(shù)據(jù)
public List<MyPoint> fixedPoints;
// 當(dāng)前方塊類型
public int blockType;
// 下一個(gè)方塊類型
public int nextBlockType;
// 方塊圖層坐標(biāo)
public MyPoint blockLayerPoint;
// 分?jǐn)?shù)
public int score;
// 最高分
public int highScore;
在構(gòu)造方法中初始化值:
public Archive()
{
fixedPoints = new List<MyPoint>();
blockType = 0;
nextBlockType = 0;
blockLayerPoint = new MyPoint(0, 0);
score = 0;
highScore = 0;
}
04.添加存檔方法
在導(dǎo)演類中添加存檔方法:
// 存檔
void SaveArchive()
{
Archive archive = new Archive();
// 固定圖層數(shù)據(jù)
if (_defaultLayer.ViewData.Count > 0)
{
archive.fixedPoints = new List<MyPoint>();
foreach (var item in _defaultLayer.ViewData)
{
archive.fixedPoints.Add(new MyPoint(item._line, item._list));
}
}
// 當(dāng)前方塊類型
// archive.blockType = 0;
// 下一個(gè)方塊類型
archive.nextBlockType = (int)_nextBlockType;
// 方塊圖層坐標(biāo)
archive.blockLayerPoint._line = _blockLayer.Point._line;
archive.blockLayerPoint._list = _blockLayer.Point._list;
// 分?jǐn)?shù)
archive.score = _currentScore;
// 最高分
archive.highScore = _highScore;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("GameSave.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, archive);
stream.Close();
}
存檔方法需要引入以下命名空間:
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
在該方法中,存儲(chǔ)當(dāng)前方塊類型被注釋掉了,因?yàn)樵趯?dǎo)演類中缺少該值,所以需要添加一個(gè)成員并存儲(chǔ)當(dāng)前方塊類型:
EBlockType _currentBlockType; // 當(dāng)前方塊類型
在初始化游戲和生成方塊中,為當(dāng)前方塊類型賦值:
// 添加初始方塊
_blockLayer.Point = new MyPoint(20, 4);
_currentBlockType = BlockCreator.GetInstance().RandomBlockType();
_blockLayer.ViewData = BlockCreator.GetInstance().CreateBlock(_currentBlockType);
// 使用上一次生成的類型創(chuàng)建方塊
_currentBlockType = _nextBlockType;
_blockLayer.ViewData = BlockCreator.GetInstance().CreateBlock(_currentBlockType);
然后將存檔方法中的注釋刪除:
// 當(dāng)前方塊類型
archive.blockType = (int)_currentBlockType;
// 下一個(gè)方塊類型
archive.nextBlockType = (int)_nextBlockType;
05.執(zhí)行存檔
在執(zhí)行之前,需要為MyPoint結(jié)構(gòu)體也添加[Serializable],否則無(wú)法成功序列化,你需要添加System引用才能使用此特性。
存檔的時(shí)機(jī),我選擇的是在游戲退出前進(jìn)行存檔:
// 游戲退出時(shí)調(diào)用
private void OnApplicationQuit()
{
SaveArchive();
}
06.測(cè)試
運(yùn)行游戲,隨便下落幾個(gè)方塊后,停止游戲。如果存檔沒(méi)有問(wèn)題的話,應(yīng)該會(huì)在游戲的根目錄(或項(xiàng)目根目錄)下生成“GameSave.bin”:

代碼鏈接:https://pan.baidu.com/s/1W7zc9ycMGwmW3ipbKAvuGg
提取碼:a5c6