文章

創建一個簡單的存檔系統

在 Unity 中創建一個簡單的存檔系統,可以讓你保存和讀取遊戲進度、設置或其他重要數據。以下是使用 JSON 進行序列化,來創建一個簡單的存檔系統的步驟。這種方法易於實現且易於閱讀和編寫。

1. 定義數據結構

首先,定義一個可以序列化的類來存儲遊戲數據。例如:

1
2
3
4
5
6
7
[System.Serializable]
public class GameData
{
    public string playerName;
    public int playerScore;
    public float playerLevel;
}

2. 創建存檔管理器腳本

創建一個腳本來處理數據的保存和讀取。這個腳本將包含保存和載入數據的功能。

步驟 1:創建腳本

  1. Assets 資料夾中,右鍵選擇 Create > C# Script,創建一個新的 C# 腳本,命名為 SaveManager

  2. 編輯 SaveManager 腳本如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    
    using UnityEngine;
    using System.IO;
    
    public class SaveManager : MonoBehaviour
    {
        private string saveFilePath;
    
        private void Awake()
        {
            // 定義存檔文件的路徑
            saveFilePath = Path.Combine(Application.persistentDataPath, "gameData.json");
        }
    
        // 保存遊戲數據
        public void SaveGame(GameData data)
        {
            string json = JsonUtility.ToJson(data, true);
            File.WriteAllText(saveFilePath, json);
            Debug.Log("Game Data Saved to " + saveFilePath);
        }
    
        // 載入遊戲數據
        public GameData LoadGame()
        {
            if (File.Exists(saveFilePath))
            {
                string json = File.ReadAllText(saveFilePath);
                GameData data = JsonUtility.FromJson<GameData>(json);
                Debug.Log("Game Data Loaded from " + saveFilePath);
                return data;
            }
            else
            {
                Debug.LogWarning("No save file found.");
                return null;
            }
        }
    }
    
    • Application.persistentDataPath 是用於存儲遊戲數據的目錄,適合用來存儲遊戲存檔。
    • JsonUtility.ToJson 將物件序列化為 JSON 字符串。
    • File.WriteAllText 將 JSON 字符串寫入文件。
    • File.ReadAllText 從文件中讀取 JSON 字符串。
    • JsonUtility.FromJson 將 JSON 字符串轉換回物件。

3. 創建遊戲管理器腳本

創建一個遊戲管理器腳本來演示如何使用 SaveManager 來保存和載入遊戲數據。

步驟 1:創建腳本

  1. Assets 資料夾中,右鍵選擇 Create > C# Script,創建一個新的 C# 腳本,命名為 GameManager

  2. 編輯 GameManager 腳本如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    
    using UnityEngine;
    using UnityEngine.UI;
    
    public class GameManager : MonoBehaviour
    {
        public SaveManager saveManager;
        public InputField nameInput;
        public InputField scoreInput;
        public InputField levelInput;
        public Text statusText;
    
        private void Start()
        {
            LoadGame();
        }
    
        public void SaveGame()
        {
            GameData data = new GameData
            {
                playerName = nameInput.text,
                playerScore = int.Parse(scoreInput.text),
                playerLevel = float.Parse(levelInput.text)
            };
    
            saveManager.SaveGame(data);
            statusText.text = "Game Saved!";
        }
    
        public void LoadGame()
        {
            GameData data = saveManager.LoadGame();
            if (data != null)
            {
                nameInput.text = data.playerName;
                scoreInput.text = data.playerScore.ToString();
                levelInput.text = data.playerLevel.ToString();
                statusText.text = "Game Loaded!";
            }
            else
            {
                statusText.text = "No Save Data Found!";
            }
        }
    }
    
    • nameInputscoreInputlevelInput 是 UI 元素,用於顯示和輸入數據。
    • statusText 用於顯示存檔和載入的狀態。

4. 設置 Unity 編輯器中的 UI

  1. 在 Unity 編輯器中,創建 UI 元素以便用戶可以輸入和顯示數據。
    • 創建 InputField 元素以供輸入玩家名字、分數和等級。
    • 創建 Button 元素來觸發保存和載入操作。
    • 創建 Text 元素來顯示狀態消息。
  2. SaveManagerGameManager 腳本附加到場景中的物件上。

  3. 將 UI 元素連接到 GameManager 腳本中的相應字段。
    • InputField 元素拖到 nameInputscoreInputlevelInput 字段中。
    • Text 元素拖到 statusText 字段中。
  4. 設置按鈕的 OnClick 事件來調用 SaveGameLoadGame 方法。

5. 小結

這樣,你就完成了一個簡單的存檔系統。你可以使用 SaveManager 來保存和載入遊戲數據,並使用 GameManager 來處理 UI 和數據的交互。這個系統可以用於保存玩家的進度、遊戲設置等,並能夠在遊戲重啟後恢復數據。

本文章以 CC BY 4.0 授權