大家開發游戲的時候或多或少,都要把輸出存放在本地,其實用很多方法可以去實現,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實例類,添加自己需要的字段,請大家多多指點............................
轉載請標明出處
