using UnityEngine;
using System;
///
/// 金币管理器,全局单例
///
public class GoldManager : MonoBehaviour
{
public static GoldManager Instance { get; private set; }
[Header("金币设置")]
[SerializeField] private int initialGold = 500;
[SerializeField] private int currentGold = 500;
///
/// 当前金币数量(只读)
///
public int CurrentGold => currentGold;
///
/// 金币变化事件(参数:新的金币数量)
///
public event Action OnGoldChanged;
private void Awake()
{
// 单例模式
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
}
private void Start()
{
currentGold = initialGold;
OnGoldChanged?.Invoke(currentGold);
}
///
/// 增加金币
///
public void AddGold(int amount)
{
if (amount <= 0) return;
currentGold += amount;
OnGoldChanged?.Invoke(currentGold);
Debug.Log($"获得金币 +{amount},当前金币: {currentGold}");
}
///
/// 尝试消费金币,如果金币足够则扣除并返回 true,否则返回 false
///
public bool TrySpendGold(int amount)
{
if (amount <= 0)
{
Debug.LogWarning("消费金币数量必须大于0");
return false;
}
if (currentGold < amount)
{
Debug.LogWarning($"金币不足!需要 {amount},当前只有 {currentGold}");
return false;
}
currentGold -= amount;
OnGoldChanged?.Invoke(currentGold);
Debug.Log($"消费金币 -{amount},当前金币: {currentGold}");
return true;
}
///
/// 检查是否有足够的金币
///
public bool HasEnoughGold(int amount)
{
return currentGold >= amount;
}
}