using System.Collections; using System.Collections.Generic; using UnityEngine; using AX.Network.Common; /// /// 实体管理器 /// public class EntitiesManager { public static readonly EntitiesManager Instance = new EntitiesManager(); //private long userId = 6431758821830431551;//用户id //private long num = 0;//自增数 private Dictionary entityMap = new Dictionary(); private Dictionary> typeMap = new Dictionary>(); /// /// 创建游戏对象,并注入到实体容器 /// /// /// /// /// /// public GameObject CreateObj(GameObject prefab, Vector3 clonePos, Transform parent, long id) { var clonedObj = GameObject.Instantiate(prefab,clonePos,Quaternion.identity,parent) as GameObject; clonedObj.GetComponent().SetGameObjID(id); AddEntity(id,clonedObj); return clonedObj; } /// /// 创建UI对象,并注入到实体容器 /// /// /// /// /// public GameObject CreateObj(GameObject prefab, Transform parent, long id) { var uiClonedObj = GameObject.Instantiate(prefab, parent) as GameObject; uiClonedObj.GetComponent().SetGameObjID(id); AddEntity(id,uiClonedObj); return uiClonedObj; } /// /// 删除实体对象,并从实体容器删除引用关系 /// /// public void DeleteObj(GameObject go) { if (SelectedObjs.selectedObj == go) { SelectedObjs.selectedObj = null; } if (SelectedObjs.gameObjs.Contains(go)) { SelectedObjs.gameObjs.Remove(go); } if (SelectedObjs.characters.Contains(go)) { SelectedObjs.characters.Remove(go); } if (SelectedObjs.selectedCharacters.Contains(go)) { SelectedObjs.selectedCharacters.Remove(go); } var gameObjID = go.GetComponent().GameObjID; RemoveEntity(gameObjID, go); GameObject.Destroy(go); } /// /// 创建游戏对象ID /// /// public long CreateObjID() { return (long)GUID.NewGuid(0, 0); } /// /// 把游戏对象注入到实体容器内 /// /// /// public void AddEntity(long id, GameObject go) { entityMap.Add(id,go); var type = go.GetComponent().gameObjType; var entities = default(IEnumerable); if (typeMap.TryGetValue(type,out entities)) { ((List)entities).Add(go); } else { var entityList = new List(); entityList.Add(go); typeMap.Add(type,entityList); } } /// /// 删除实体容器中的游戏实例 /// /// /// public void RemoveEntity(long id, GameObject go) { entityMap.Remove(id); var type = go.GetComponent().gameObjType; var entities = default(IEnumerable); if (typeMap.TryGetValue(type, out entities)) { ((List)entities).Remove(go); } } /// /// 根据游戏对象ID查找某个游戏对象 /// /// /// public GameObject GetEntityByID(long id) { GameObject go = null; entityMap.TryGetValue(id,out go);//没找到返回null,否则返回go return go; } /// /// 根据类型查找某一类游戏对象的集合 /// /// /// public IEnumerable GetEntitiesByType(CloneObjType type) { var entities = default(IEnumerable); typeMap.TryGetValue(type,out entities);//没找到返回没有元数据的默认集合entities,否则返回带有元数据的集合entities return entities; } public void Reset() { entityMap.Clear(); typeMap.Clear(); } }