using UnityEngine; using System; using TMPro; using Player.Wallet; // 添加命名空间 public class GameDataManager : MonoBehaviour { public static GameDataManager Instance { get; private set; } public int coins { get; private set; } public Action onCoinsChanged; [SerializeField] private TextMeshProUGUI gameSceneCoinsText; // 引用游戏场景中的金币文本 private void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); // 尝试从ComponentsManager获取金币数量 if (ComponentsManager.PlayerWallet != null) { coins = ComponentsManager.PlayerWallet.GetMoney; } else { // 如果ComponentsManager不可用,则从PlayerPrefs加载 coins = PlayerPrefs.GetInt("_playerMoney", 0); } } else { Destroy(gameObject); } } private void Start() { // 从PlayerPrefs加载保存的金币数据 if (ComponentsManager.PlayerWallet != null) { coins = ComponentsManager.PlayerWallet.GetMoney; } else { coins = PlayerPrefs.GetInt("_playerMoney", 0); } // 通知所有监听者更新显示 onCoinsChanged?.Invoke(); } public void UpdateCoins(int amount) { coins = amount; onCoinsChanged?.Invoke(); // 同步到游戏场景的金币显示 if (gameSceneCoinsText != null) { gameSceneCoinsText.text = $"{coins}"; } // 如果PlayerWallet可用,同步到PlayerWallet if (ComponentsManager.PlayerWallet != null) { // 先减去当前金币 ComponentsManager.PlayerWallet.UseMoney(ComponentsManager.PlayerWallet.GetMoney); // 再添加新的金币数量 ComponentsManager.PlayerWallet.AddMoney(coins); } } public void AddCoins(int amount) { coins += amount; onCoinsChanged?.Invoke(); // 同步到游戏场景的金币显示 if (gameSceneCoinsText != null) { gameSceneCoinsText.text = $"{coins}"; } // 如果PlayerWallet可用,同步到PlayerWallet if (ComponentsManager.PlayerWallet != null) { ComponentsManager.PlayerWallet.AddMoney(amount); } } // 设置游戏场景中的金币文本引用 public void SetGameSceneCoinsText(TextMeshProUGUI coinsText) { gameSceneCoinsText = coinsText; // 立即更新显示 if (gameSceneCoinsText != null) { gameSceneCoinsText.text = $"{coins}"; } } }