改良版程式碼會在遊戲開始時從文字檔讀取卡牌數據,並存入 二維陣列 (GameCard[,]) 另外,也提供範例文字檔格式,可以依照這個格式新增卡牌數據。 1. 文字檔範例 (cards.txt) 請把這個檔案放在 StreamingAssets 資料夾內 (Assets/StreamingAssets/cards.txt),確保 Unity 能夠讀取它。 火龍,火,2500,2000 水精靈,水,1800,2200 森林妖精,草,2000,1500 雷鳴獵豹,雷,2300,1700 冰雪狼,冰,2100,1900 岩石巨人,岩,2700,2400 2. 修改後的 C# 程式碼 / 讀取 cards.txt,將資料存入 二維陣列,然後顯示在 TextMeshProUGUI 介面上。 using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using System.IO; // 讀取文字檔案 public class CardDatabase : MonoBehaviour { public TextMeshProUGUI textDisplay; // UI 文字物件 (需手動設定) private GameCard[,] cards; // 二維陣列存放卡牌 private int rows = 2; // 設定二維陣列的行數 private int cols = 3; // 設定二維陣列的列數 void Start() { LoadCardsFromFile(); DisplayCards(); } void LoadCardsFromFile() { string filePath = Path.Combine(Application.streamingAssetsPath, "cards.txt"); if (File.Exists(filePath)) { string[] lines = File.ReadAllLines(filePath); cards = new GameCard[rows, cols]; // 初始化二維陣列 int index = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (index < lines.Length) // 確保不超出範圍 { string[] data = lines[index].Split(','); if (data.Length == 4) // 確保資料格式正確 { string name = data[0]; string type = data[1]; int attack = int.Parse(data[2]); int defense = int.Parse(data[3]); cards[i, j] = new GameCard(name, type, attack, defense); } index++; } } } } else { Debug.LogError("找不到卡牌資料檔案:" + filePath); } } void DisplayCards() { if (textDisplay != null) { textDisplay.text = ""; // 清空文字 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (cards[i, j] != null) { textDisplay.text += cards[i, j].ToString() + "\n"; } } } } else { Debug.LogError("請將 TextMeshProUGUI 物件指派給 textDisplay!"); } } } 3. GameCard 類別 / 如果還沒有 GameCard 類別,可以使用這個版本: public class GameCard { public string Name { get; private set; } public string Type { get; private set; } public int Attack { get; private set; } public int Defense { get; private set; } public GameCard(string name, string type, int attack, int defense) { Name = name; Type = type; Attack = attack; Defense = defense; } public override string ToString() { return $"{Name} ({Type}) - ATK: {Attack}, DEF: {Defense}"; } } 修改後的功能 讀取 cards.txt 內的卡牌數據 將卡片存入 GameCard[,] 二維陣列 顯示卡片資訊到 UI (TextMeshProUGUI) 支援不同數量的卡牌,只要 rows 和 cols 設定合理