[unity 本地数据存储] 单机小游戏本地数据保存 BinaryFormatter
大家开发游戏的时候或多或少,都要把输出存放在本地,其实用很多方法可以去实现,unity 自身带的API 就有此功能 如:
PlayerPrefs.SetInt(“”,1)
PlayerPrefs.SetFloat(“”,0.2f)
PlayerPrefs.SetString("","")
PlayerPrefs.GetInt("");
PlayerPrefs.GetFloat("");
PlayerPrefs.GetString("");
大家也可以通过 xml/text/jion 来实现存储功能,
大家也可以通过序列化和反序列来存储,把整个对象实例化保存,代码如下
[Serializable]
public class PlayerData
{
private bool isFristOpen = false;
private List<int> data = new List<int>();
private List<Item> itemData = new List<Item>();
public List<int> Data
{
get
{
return data;
}
set
{
data = value;
}
}
public List<Item> ItemData
{
get
{
return itemData;
}
set
{
itemData = value;
}
}
public bool IsFristOpen
{
get
{
return isFristOpen;
}
set
{
isFristOpen = value;
}
}
}
[Serializable]
public class Item
{
private int index;
private int value;
public int Index
{
get
{
return index;
}
set
{
index = value;
}
}
public int Value
{
get
{
return value;
}
set
{
this.value = value;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class GameData : MonoBehaviour
{
private PlayerData player;
private void Awake()
{
readData();
if (!player.IsFristOpen)
{
player.IsFristOpen = true;
}
saveData();
}
/// <summary>
/// 保存数据到配置表(序列化)
/// </summary>
public void saveData()
{
try
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fs = File.Create(Application.persistentDataPath + "/PlayerData.data"))
{
if (player == null)
{
player = new PlayerData();
}
bf.Serialize(fs, player);
}
}
catch (System.Exception e)
{
Debug.LogError(e.Message);
}
}
/// <summary>
/// 读取数据到缓存(反序列化)
/// </summary>
public void readData()
{
try
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fs = File.Open(Application.persistentDataPath + "/PlayerData.data", FileMode.Open))
{
player = (PlayerData)bf.Deserialize(fs);
}
}
catch
{
player = new PlayerData();
readData();
}
}
}
经过测试可以正常使用,可以根据自己的需求来改变PlayerData和ItemData实例类,添加自己需要的字段,请大家多多指点............................
转载请标明出处

浙公网安备 33010602011771号