using System; using System.Collections.Generic; using Framework; namespace Gameplay.Common { public class GameUnitMapper { private static GameUnitMapper _instance; public static GameUnitMapper Inst { get { return _instance; } } public static GameUnitMapper CreateInstance() { if (_instance != null) { DebugUtil.LogError("请勿重复创建: GameUnitMapper"); return _instance; } _instance = new GameUnitMapper(); return _instance; } private readonly Dictionary _gameUnitDict; private readonly List _unitList; public List unitList { get { return _unitList; } } private GameUnitMapper() { _unitList = new List(); _gameUnitDict = new Dictionary(); } public GameUnit GetUnitById(uint uId) { if (_gameUnitDict.TryGetValue(uId, out var unit)) { return unit; } DebugUtil.Log("不存在的UnitId: {0}", uId); return null; } public void RemoveUnitById(uint uId) { if (_gameUnitDict.TryGetValue(uId, out var unit)) { _gameUnitDict.Remove(uId); _unitList.Remove(unit); } else { DebugUtil.Log("不存在的UnitId: {0}", uId); } } public void Init() { EventManager.Instance.Register(EventManager.EventName.UnitCreate, (Action)_AddUnit); EventManager.Instance.Register(EventManager.EventName.UnitDispose, (Action)_RemoveUnit); } public void Dispose() { EventManager.Instance.Unregister(EventManager.EventName.UnitCreate, (Action)_AddUnit); EventManager.Instance.Unregister(EventManager.EventName.UnitDispose, (Action)_RemoveUnit); _gameUnitDict.Clear(); _unitList.Clear(); _instance = null; } private void _AddUnit(GameUnit unit) { if (_gameUnitDict.ContainsKey(unit.GetID())) { DebugUtil.LogError("重复的UnitId: {0}",unit.GetID()); return; } _unitList.Add(unit); _gameUnitDict.Add(unit.GetID(), unit); } private void _RemoveUnit(uint id) { if (!_gameUnitDict.ContainsKey(id)) { DebugUtil.LogError("不存在的UnitId: {0}", id); return; } _unitList.Remove(_gameUnitDict[id]); _gameUnitDict.Remove(id); } } }