GameDataManager.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using UnityEngine;
  2. using System;
  3. using TMPro;
  4. using Player.Wallet; // 添加命名空间
  5. public class GameDataManager : MonoBehaviour
  6. {
  7. public static GameDataManager Instance { get; private set; }
  8. public int coins { get; private set; }
  9. public Action onCoinsChanged;
  10. [SerializeField] private TextMeshProUGUI gameSceneCoinsText; // 引用游戏场景中的金币文本
  11. private void Awake()
  12. {
  13. if (Instance == null)
  14. {
  15. Instance = this;
  16. DontDestroyOnLoad(gameObject);
  17. // 尝试从ComponentsManager获取金币数量
  18. if (ComponentsManager.PlayerWallet != null)
  19. {
  20. coins = ComponentsManager.PlayerWallet.GetMoney;
  21. }
  22. else
  23. {
  24. // 如果ComponentsManager不可用,则从PlayerPrefs加载
  25. coins = PlayerPrefs.GetInt("_playerMoney", 0);
  26. }
  27. }
  28. else
  29. {
  30. Destroy(gameObject);
  31. }
  32. }
  33. private void Start()
  34. {
  35. // 从PlayerPrefs加载保存的金币数据
  36. if (ComponentsManager.PlayerWallet != null)
  37. {
  38. coins = ComponentsManager.PlayerWallet.GetMoney;
  39. }
  40. else
  41. {
  42. coins = PlayerPrefs.GetInt("_playerMoney", 0);
  43. }
  44. // 通知所有监听者更新显示
  45. onCoinsChanged?.Invoke();
  46. }
  47. public void UpdateCoins(int amount)
  48. {
  49. coins = amount;
  50. onCoinsChanged?.Invoke();
  51. // 同步到游戏场景的金币显示
  52. if (gameSceneCoinsText != null)
  53. {
  54. gameSceneCoinsText.text = $"{coins}";
  55. }
  56. // 如果PlayerWallet可用,同步到PlayerWallet
  57. if (ComponentsManager.PlayerWallet != null)
  58. {
  59. // 先减去当前金币
  60. ComponentsManager.PlayerWallet.UseMoney(ComponentsManager.PlayerWallet.GetMoney);
  61. // 再添加新的金币数量
  62. ComponentsManager.PlayerWallet.AddMoney(coins);
  63. }
  64. }
  65. public void AddCoins(int amount)
  66. {
  67. coins += amount;
  68. onCoinsChanged?.Invoke();
  69. // 同步到游戏场景的金币显示
  70. if (gameSceneCoinsText != null)
  71. {
  72. gameSceneCoinsText.text = $"{coins}";
  73. }
  74. // 如果PlayerWallet可用,同步到PlayerWallet
  75. if (ComponentsManager.PlayerWallet != null)
  76. {
  77. ComponentsManager.PlayerWallet.AddMoney(amount);
  78. }
  79. }
  80. // 设置游戏场景中的金币文本引用
  81. public void SetGameSceneCoinsText(TextMeshProUGUI coinsText)
  82. {
  83. gameSceneCoinsText = coinsText;
  84. // 立即更新显示
  85. if (gameSceneCoinsText != null)
  86. {
  87. gameSceneCoinsText.text = $"{coins}";
  88. }
  89. }
  90. }