用一个 _isStopped 布尔门替代 id 追踪: - OnReset 开头置 _isStopped = true - OnInit 置 _isStopped = false - OnShowEntitySuccess:只要 _isStopped 为真且是 Enemy 组,立即 HideEntity - SpawnEnemyAsync await 恢复后也补一道 _isStopped 检查(若 await 拿到了 enemy 且已停战,直接 hide 不注册)——双保险 为什么这样对:停战窗口(Shop/LevelUp)期间本就不该有任何敌人,所以"停战期间出生的敌人一律 hide"在语义上完全正确,且不受 await 同步抽空、id 复用、加载时序任何影响。
59 lines
1.5 KiB
C#
59 lines
1.5 KiB
C#
using System.Collections.Generic;
|
|
using SepCore.Entity;
|
|
|
|
namespace SepCore.EnemyManager
|
|
{
|
|
public class EnemyRegistry
|
|
{
|
|
private readonly Dictionary<int, EntityBase> _enemyById;
|
|
|
|
public int Count => _enemyById.Count;
|
|
public IReadOnlyCollection<EntityBase> Enemies => _enemyById.Values;
|
|
|
|
public EnemyRegistry()
|
|
{
|
|
_enemyById = new Dictionary<int, EntityBase>();
|
|
}
|
|
|
|
public void Register(EnemyBase enemy)
|
|
{
|
|
if (enemy == null) return;
|
|
_enemyById[enemy.Id] = enemy;
|
|
}
|
|
|
|
public void Remove(int entityId)
|
|
{
|
|
// 移除是幂等的。ClearEnemies 会同步清空 registry,而 HideEntity 的完成回调
|
|
// 是异步的,晚几帧才到达,此时该 id 早已不在集合中,属正常情况,静默忽略即可。
|
|
_enemyById.Remove(entityId);
|
|
}
|
|
|
|
public bool TryGet(int entityId, out EntityBase enemy)
|
|
{
|
|
return _enemyById.TryGetValue(entityId, out enemy);
|
|
}
|
|
|
|
public void PruneInvalidEntries()
|
|
{
|
|
var invalidIds = new List<int>();
|
|
foreach (var kvp in _enemyById)
|
|
{
|
|
if (kvp.Value == null || !kvp.Value.Available)
|
|
{
|
|
invalidIds.Add(kvp.Key);
|
|
}
|
|
}
|
|
|
|
foreach (int id in invalidIds)
|
|
{
|
|
_enemyById.Remove(id);
|
|
}
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
_enemyById.Clear();
|
|
}
|
|
}
|
|
}
|