這段代碼的結構是為了實現 數據的封裝和管理,特別是在 Unity 中保存和加載玩家數據時。以下是對代碼設計的逐步解釋:
1.?PlayerCoin
?類
PlayerCoin
是一個簡單的數據類,用于表示單個玩家的硬幣信息。它包含以下字段:
-
count
:玩家擁有的硬幣數量。 -
name
:玩家的名字。 -
isWinner
:表示玩家是否獲勝。
-
[System.Serializable]
:這個屬性告訴 Unity 這個類可以被序列化(即將其數據轉換為 JSON 或其他格式)。這是 Unity 中保存數據的必要步驟。
2.?PlayerCoinList
?類
PlayerCoinList
是一個容器類,用于管理多個 PlayerCoin
對象。它包含一個 List<PlayerCoin>
,用于存儲玩家數據。
-
List<PlayerCoin>
:這是一個動態數組,可以存儲任意數量的PlayerCoin
對象。 -
[System.Serializable]
:同樣需要這個屬性,因為 Unity 需要將整個PlayerCoinList
對象序列化為 JSON。
3.?DataSaveManager
?類
DataSaveManager
是一個 Unity 的 MonoBehaviour
,用于管理數據的保存和加載。它包含一個 PlayerCoinList
對象,用于存儲和操作玩家數據。
-
MonoBehaviour
:這是 Unity 中所有腳本的基類,允許腳本附加到游戲對象上。 -
PlayerCoinList list
:這是一個實例化的PlayerCoinList
對象,用于存儲玩家數據。
為什么這樣設計?
1. 數據封裝
-
PlayerCoin
:表示單個玩家的數據。 -
PlayerCoinList
:表示多個玩家的數據集合。 -
DataSaveManager
:負責管理這些數據的保存和加載。
這種分層設計的好處是:
-
數據結構清晰,易于擴展。
-
每個類都有明確的職責,代碼更易于維護。
2. 序列化的需求
Unity 的 JsonUtility
類只能序列化帶有 [System.Serializable]
屬性的類。因此:
-
PlayerCoin
和PlayerCoinList
都需要標記為[System.Serializable]
。 -
PlayerCoinList
是一個“根對象”,因為JsonUtility
需要一個根對象來序列化整個數據結構。
3. Unity 的 JSON 限制
Unity 的 JsonUtility
不能直接序列化 List<T>
或數組,因此需要將 List<PlayerCoin>
包裝在一個類(如 PlayerCoinList
)中,作為序列化的根對象。
using UnityEngine;
using System.Collections.Generic;
using System.IO;[System.Serializable]
public class PlayerCoin
{public int count;public string name;public bool isWinner;
}[System.Serializable]
public class PlayerCoinList
{public List<PlayerCoin> playerCoinList = new List<PlayerCoin>();
}public class DataSaveManager : MonoBehaviour
{public PlayerCoinList list = new PlayerCoinList();void Start(){// 添加示例數據PlayerCoin player1 = new PlayerCoin();player1.count = 100;player1.name = "Player1";player1.isWinner = true;PlayerCoin player2 = new PlayerCoin();player2.count = 50;player2.name = "Player2";player2.isWinner = false;list.playerCoinList.Add(player1);list.playerCoinList.Add(player2);// 保存數據SaveData();// 加載數據LoadData();}void SaveData(){// 將對象序列化為 JSONstring json = JsonUtility.ToJson(list);// 將 JSON 數據寫入文件string filePath = Application.persistentDataPath + "/playerData.json";File.WriteAllText(filePath, json);Debug.Log("Data saved to: " + filePath);}void LoadData(){string filePath = Application.persistentDataPath + "/playerData.json";// 檢查文件是否存在if (File.Exists(filePath)){// 讀取 JSON 數據string json = File.ReadAllText(filePath);// 反序列化 JSON 數據list = JsonUtility.FromJson<PlayerCoinList>(json);Debug.Log("Data loaded from: " + filePath);}else{Debug.Log("File not found: " + filePath);}}
}