86 lines
2.4 KiB
C#
86 lines
2.4 KiB
C#
using System;
|
|
using GameFramework.Event;
|
|
using GeometryTD.CustomEvent;
|
|
using GeometryTD.Entity.EntityData;
|
|
using UnityEngine;
|
|
using UnityGameFramework.Runtime;
|
|
|
|
namespace GeometryTD.Map
|
|
{
|
|
public sealed class MapCombatRuntimeBridge
|
|
{
|
|
private Func<int, bool> _tryConsumeCoin;
|
|
private Action<int> _addCoin;
|
|
private bool _isCoinEventSubscribed;
|
|
|
|
public int CurrentCoin { get; private set; }
|
|
|
|
public void Initialize(MapEntityLoadContext loadContext, string mapName)
|
|
{
|
|
Reset();
|
|
|
|
MapData mapData = loadContext?.InitialMapData;
|
|
CurrentCoin = Mathf.Max(0, mapData != null ? mapData.InitialCoin : 0);
|
|
_tryConsumeCoin = loadContext?.TryConsumeCoin;
|
|
_addCoin = loadContext?.AddCoin;
|
|
|
|
if (_tryConsumeCoin == null || _addCoin == null)
|
|
{
|
|
Log.Warning(
|
|
"Map combat runtime bridge has incomplete callbacks. Map='{0}', TryConsumeCoin={1}, AddCoin={2}.",
|
|
mapName,
|
|
_tryConsumeCoin != null,
|
|
_addCoin != null);
|
|
}
|
|
|
|
GameEntry.Event.Subscribe(CombatCoinChangedEventArgs.EventId, OnCombatCoinChanged);
|
|
_isCoinEventSubscribed = true;
|
|
}
|
|
|
|
public void Reset()
|
|
{
|
|
if (_isCoinEventSubscribed)
|
|
{
|
|
GameEntry.Event.Unsubscribe(CombatCoinChangedEventArgs.EventId, OnCombatCoinChanged);
|
|
_isCoinEventSubscribed = false;
|
|
}
|
|
|
|
_tryConsumeCoin = null;
|
|
_addCoin = null;
|
|
CurrentCoin = 0;
|
|
}
|
|
|
|
public bool TryConsumeCoin(int cost)
|
|
{
|
|
int requiredCoin = Mathf.Max(0, cost);
|
|
if (requiredCoin <= 0)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
return _tryConsumeCoin != null && _tryConsumeCoin.Invoke(requiredCoin);
|
|
}
|
|
|
|
public void AddCoin(int coin)
|
|
{
|
|
int amount = Mathf.Max(0, coin);
|
|
if (amount <= 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_addCoin?.Invoke(amount);
|
|
}
|
|
|
|
private void OnCombatCoinChanged(object sender, GameEventArgs e)
|
|
{
|
|
if (e is not CombatCoinChangedEventArgs args)
|
|
{
|
|
return;
|
|
}
|
|
|
|
CurrentCoin = Mathf.Max(0, args.CurrentCoin);
|
|
}
|
|
}
|
|
}
|