vampire-like/Assets/GameMain/Scripts/Runtime/CustomComponent/EnemyManager/EnemyRegistry.cs

59 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
}
}
}