GameObjectManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System;
  5. public class GameObjectManager
  6. {
  7. static Vector3 s_OutOfRange = new Vector3(9000, 9000, 9000);
  8. private static Transform s_poolParent;
  9. public static Transform PoolParent
  10. {
  11. get
  12. {
  13. if (s_poolParent == null)
  14. {
  15. GameObject instancePool = new GameObject("ObjectPool");
  16. s_poolParent = instancePool.transform;
  17. if (Application.isPlaying)
  18. GameObject.DontDestroyOnLoad(s_poolParent);
  19. }
  20. return s_poolParent;
  21. }
  22. }
  23. #region 旧版本对象池
  24. private static Dictionary<string, List<GameObject>> createPools = new Dictionary<string, List<GameObject>>();
  25. private static Dictionary<string, List<GameObject>> recyclePools = new Dictionary<string, List<GameObject>>();
  26. public static Dictionary<string, List<GameObject>> GetCreatePool()
  27. {
  28. return createPools;
  29. }
  30. public static Dictionary<string, List<GameObject>> GetRecyclePool()
  31. {
  32. return recyclePools;
  33. }
  34. /// <summary>
  35. /// 加载一个对象并把它实例化
  36. /// </summary>
  37. /// <param name="gameObjectName">对象名</param>
  38. /// <param name="parent">对象的父节点,可空</param>
  39. /// <returns></returns>
  40. private static GameObject NewGameObject(string gameObjectName, GameObject parent = null)
  41. {
  42. GameObject goTmp = AssetsPoolManager.Load<GameObject>(gameObjectName);
  43. if (goTmp == null)
  44. {
  45. throw new Exception("CreateGameObject error dont find :" + gameObjectName);
  46. }
  47. return ObjectInstantiate(goTmp, parent);
  48. }
  49. private static GameObject ObjectInstantiate(GameObject prefab, GameObject parent = null)
  50. {
  51. if (prefab == null)
  52. {
  53. throw new Exception("CreateGameObject error : l_prefab is null");
  54. }
  55. Transform transform = parent == null ? null : parent.transform;
  56. GameObject instanceTmp = GameObject.Instantiate(prefab, transform);
  57. instanceTmp.name = prefab.name;
  58. return instanceTmp;
  59. }
  60. public static bool IsExist(string objectName)
  61. {
  62. if (string.IsNullOrEmpty(objectName))
  63. {
  64. Debug.LogError("GameObjectManager objectName is null!");
  65. return false;
  66. }
  67. if (recyclePools.ContainsKey(objectName) && recyclePools[objectName].Count > 0)
  68. {
  69. return true;
  70. }
  71. return false;
  72. }
  73. //判断是否在对象池中
  74. public static bool IsExist(GameObject go)
  75. {
  76. if (recyclePools.ContainsKey(go.name) && recyclePools[go.name].Count > 0)
  77. {
  78. return recyclePools[go.name].Contains(go);
  79. }
  80. else
  81. {
  82. return false;
  83. }
  84. }
  85. public static GameObject CreateGameObject(string name, GameObject parent = null, bool isSetActive = true)
  86. {
  87. return GetNewObject(true, name, null, parent, isSetActive);
  88. }
  89. public static GameObject CreateGameObject(GameObject prefab, GameObject parent = null, bool isSetActive = true)
  90. {
  91. return GetNewObject(true, null, prefab, parent, isSetActive);
  92. }
  93. /// <summary>
  94. /// 从对象池取出一个对象,如果没有,则直接创建它
  95. /// </summary>
  96. /// <param name="name">对象名</param>
  97. /// <param name="parent">要创建到的父节点</param>
  98. /// <returns>返回这个对象</returns>
  99. public static GameObject CreateGameObjectByPool(string name, GameObject parent = null, bool isSetActive = true)
  100. {
  101. return GetNewObject(false, name, null, parent, isSetActive);
  102. }
  103. public static GameObject CreateGameObjectByPool(GameObject prefab, GameObject parent = null, bool isSetActive = true)
  104. {
  105. return GetNewObject(false, null, prefab, parent, isSetActive);
  106. }
  107. private static GameObject GetNewObject(bool isAlwaysNew, string objName, GameObject prefab, GameObject parent = null, bool isSetActive = true)
  108. {
  109. GameObject go = null;
  110. string name = objName;
  111. if (string.IsNullOrEmpty(name))
  112. {
  113. name = prefab.name;
  114. }
  115. if (!isAlwaysNew && IsExist(name))
  116. {
  117. go = recyclePools[name][0];
  118. recyclePools[name].RemoveAt(0);
  119. AssetsPoolManager.MarkeFlag(name, typeof(GameObject));
  120. }
  121. else
  122. {
  123. if (prefab == null && !string.IsNullOrEmpty(objName))
  124. {
  125. go = NewGameObject(name, parent);
  126. if (createPools.ContainsKey(name))
  127. {
  128. createPools[name].Add(go);
  129. }
  130. else
  131. {
  132. createPools.Add(name, new List<GameObject>() { go });
  133. }
  134. }
  135. else if (prefab != null && string.IsNullOrEmpty(objName))
  136. {
  137. go = ObjectInstantiate(prefab, parent);
  138. }
  139. }
  140. PoolObject po = go.GetComponent<PoolObject>();
  141. if (po)
  142. {
  143. try
  144. {
  145. po.OnFetch();
  146. }
  147. catch(Exception e)
  148. {
  149. Debug.LogError("GetNewObject Error: " + e.ToString());
  150. }
  151. }
  152. if (isSetActive)
  153. go.SetActive(true);
  154. if (parent == null)
  155. {
  156. go.transform.SetParent(null);
  157. }
  158. else
  159. {
  160. go.transform.SetParent(parent.transform);
  161. }
  162. return go;
  163. }
  164. /// <summary>
  165. /// 将一个对象放入对象池
  166. /// </summary>
  167. /// <param name="go"></param>
  168. /// <param name="isSetInactive">是否将放入的物体设为不激活状态(obj.SetActive(false))</param>
  169. public static void DestroyGameObjectByPool(GameObject go, bool isSetInactive = true)
  170. {
  171. if (go == null)
  172. return;
  173. string key = go.name.Replace("(Clone)", "");
  174. if (recyclePools.ContainsKey(key) == false)
  175. {
  176. recyclePools.Add(key, new List<GameObject>());
  177. }
  178. if (recyclePools[key].Contains(go))
  179. {
  180. Debug.LogError("DestroyGameObjectByPool:-> Repeat Destroy GameObject !" + go);
  181. return;
  182. }
  183. recyclePools[key].Add(go);
  184. if (isSetInactive)
  185. go.SetActive(false);
  186. else
  187. {
  188. go.transform.position = s_OutOfRange;
  189. }
  190. go.name = key;
  191. go.transform.SetParent(PoolParent);
  192. PoolObject po = go.GetComponent<PoolObject>();
  193. if (po)
  194. {
  195. po.OnRecycle();
  196. }
  197. if (createPools.ContainsKey(key) && createPools[key].Contains(go))
  198. {
  199. createPools[key].Remove(go);
  200. }
  201. }
  202. /// <summary>
  203. /// 立即摧毁克隆体
  204. /// </summary>
  205. /// <param name="go"></param>
  206. public static void DestroyGameObject(GameObject go)
  207. {
  208. if (go == null)
  209. return;
  210. string key = go.name.Replace("(Clone)", "");
  211. PoolObject po = go.GetComponent<PoolObject>();
  212. if (po)
  213. {
  214. po.OnObjectDestroy();
  215. }
  216. if (createPools.ContainsKey(key) && createPools[key].Contains(go))
  217. {
  218. createPools[key].Remove(go);
  219. }
  220. UnityEngine.Object.Destroy(go);
  221. }
  222. public static void DestroyGameObjectByPool(GameObject go, float time)
  223. {
  224. Timer.DelayCallBack(time, (object[] obj) =>
  225. {
  226. if (go != null)//应对调用过CleanPool()
  227. DestroyGameObjectByPool(go);
  228. });
  229. }
  230. private static List<string> removeObjList = new List<string>();
  231. /// <summary>
  232. /// 清空对象池
  233. /// </summary>
  234. public static void CleanPool()
  235. {
  236. //Debug.LogWarning("清空对象池");
  237. removeObjList.Clear();
  238. foreach(string name in createPools.Keys)
  239. {
  240. //if (recyclePools.ContainsKey(name))
  241. //{
  242. // List<GameObject> l_objList = recyclePools[name];
  243. // for (int i = 0; i < l_objList.Count; i++)
  244. // {
  245. // GameObject go = l_objList[i];
  246. // PoolObject po = go.GetComponent<PoolObject>();
  247. // if (po)
  248. // {
  249. // po.OnObjectDestroy();
  250. // }
  251. // GameObject.Destroy(go);
  252. // }
  253. // l_objList.Clear();
  254. // recyclePools.Remove(name);
  255. //}
  256. if(createPools[name].Count == 0)
  257. {
  258. removeObjList.Add(name);
  259. AssetsPoolManager.DestroyByPool(name);
  260. }
  261. }
  262. foreach (var item in removeObjList)
  263. {
  264. createPools.Remove(item);
  265. }
  266. foreach (var name in recyclePools.Keys)
  267. {
  268. List<GameObject> l_objList = recyclePools[name];
  269. for (int i = 0; i < l_objList.Count; i++)
  270. {
  271. GameObject go = l_objList[i];
  272. PoolObject po = go.GetComponent<PoolObject>();
  273. if (po)
  274. {
  275. po.OnObjectDestroy();
  276. }
  277. GameObject.Destroy(go);
  278. }
  279. l_objList.Clear();
  280. }
  281. recyclePools.Clear();
  282. }
  283. /// <summary>
  284. /// 清除掉某一个对象的所有对象池缓存
  285. /// </summary>
  286. public static void CleanPoolByName(string name)
  287. {
  288. Debug.Log("CleanPool :" + name);
  289. if (recyclePools.ContainsKey(name))
  290. {
  291. List<GameObject> l_objList = recyclePools[name];
  292. for (int i = 0; i < l_objList.Count; i++)
  293. {
  294. GameObject go = l_objList[i];
  295. PoolObject po = go.GetComponent<PoolObject>();
  296. if (po)
  297. {
  298. po.OnObjectDestroy();
  299. }
  300. GameObject.Destroy(go);
  301. }
  302. l_objList.Clear();
  303. recyclePools.Remove(name);
  304. }
  305. if (createPools[name].Count == 0)
  306. {
  307. createPools.Remove(name);
  308. AssetsPoolManager.DestroyByPool(name);
  309. }
  310. }
  311. #endregion
  312. #region 旧版本对象池 异步方法
  313. //public static void CreateGameObjectByPoolAsync(string name, CallBack<GameObject> callback, GameObject parent = null, bool isSetActive = true)
  314. //{
  315. // AssetsPoolManager.LoadAsync(name,null, (status, res) =>
  316. // {
  317. // if(status.isDone)
  318. // {
  319. // try
  320. // {
  321. // callback(CreateGameObjectByPool(name, parent, isSetActive));
  322. // }
  323. // catch (Exception e)
  324. // {
  325. // Debug.LogError("CreateGameObjectByPoolAsync Exception: " + e.ToString());
  326. // }
  327. // }
  328. // });
  329. //}
  330. #endregion
  331. //#region 新版本对象池
  332. //static Dictionary<string, List<PoolObject>> s_objectPool_new = new Dictionary<string, List<PoolObject>>();
  333. ///// <summary>
  334. ///// 加载一个对象并把它实例化
  335. ///// </summary>
  336. ///// <param name="gameObjectName">对象名</param>
  337. ///// <param name="parent">对象的父节点,可空</param>
  338. ///// <returns></returns>
  339. //static PoolObject CreatePoolObject(string gameObjectName, GameObject parent = null)
  340. //{
  341. // GameObject go = ResourceManager.Load<GameObject>(gameObjectName);
  342. // if (go == null)
  343. // {
  344. // throw new Exception("CreatPoolObject error dont find : ->" + gameObjectName + "<-");
  345. // }
  346. // GameObject instanceTmp = Instantiate(go);
  347. // instanceTmp.name = go.name;
  348. // PoolObject po = instanceTmp.GetComponent<PoolObject>();
  349. // if (po == null)
  350. // {
  351. // throw new Exception("CreatPoolObject error : ->" + gameObjectName + "<- not is PoolObject !");
  352. // }
  353. // po.OnCreate();
  354. // if (parent != null)
  355. // {
  356. // instanceTmp.transform.SetParent(parent.transform);
  357. // }
  358. // instanceTmp.SetActive(true);
  359. // return po;
  360. //}
  361. ///// <summary>
  362. ///// 把一个对象放入对象池
  363. ///// </summary>
  364. ///// <param name="gameObjectName"></param>
  365. //public static void PutPoolObject(string gameObjectName)
  366. //{
  367. // DestroyPoolObject(CreatePoolObject(gameObjectName));
  368. //}
  369. ///// <summary>
  370. ///// 预存入对象池
  371. ///// </summary>
  372. ///// <param name="name"></param>
  373. //public static void PutPoolGameOject(string name)
  374. //{
  375. // DestroyGameObjectByPool(CreateGameObjectByPool(name));
  376. //}
  377. //public static bool IsExist_New(string objectName)
  378. //{
  379. // if (objectName == null)
  380. // {
  381. // Debug.LogError("IsExist_New error : objectName is null!");
  382. // return false;
  383. // }
  384. // if (s_objectPool_new.ContainsKey(objectName) && s_objectPool_new[objectName].Count > 0)
  385. // {
  386. // return true;
  387. // }
  388. // return false;
  389. //}
  390. ///// <summary>
  391. ///// 从对象池取出一个对象,如果没有,则直接创建它
  392. ///// </summary>
  393. ///// <param name="name">对象名</param>
  394. ///// <param name="parent">要创建到的父节点</param>
  395. ///// <returns>返回这个对象</returns>
  396. //public static PoolObject GetPoolObject(string name, GameObject parent = null)
  397. //{
  398. // PoolObject po;
  399. // if (IsExist_New(name))
  400. // {
  401. // po = s_objectPool_new[name][0];
  402. // s_objectPool_new[name].RemoveAt(0);
  403. // if (po && po.SetActive)
  404. // po.gameObject.SetActive(true);
  405. // if (parent == null)
  406. // {
  407. // po.transform.SetParent(null);
  408. // }
  409. // else
  410. // {
  411. // po.transform.SetParent(parent.transform);
  412. // }
  413. // }
  414. // else
  415. // {
  416. // po = CreatePoolObject(name, parent);
  417. // }
  418. // po.OnFetch();
  419. // return po;
  420. //}
  421. ///// <summary>
  422. ///// 将一个对象放入对象池
  423. ///// </summary>
  424. ///// <param name="obj">目标对象</param>
  425. //public static void DestroyPoolObject(PoolObject obj)
  426. //{
  427. // string key = obj.name.Replace("(Clone)", "");
  428. // if (s_objectPool_new.ContainsKey(key) == false)
  429. // {
  430. // s_objectPool_new.Add(key, new List<PoolObject>());
  431. // }
  432. // if (s_objectPool_new[key].Contains(obj))
  433. // {
  434. // throw new Exception("DestroyPoolObject:-> Repeat Destroy GameObject !" + obj);
  435. // }
  436. // s_objectPool_new[key].Add(obj);
  437. // if (obj.SetActive)
  438. // obj.gameObject.SetActive(false);
  439. // else
  440. // obj.transform.position = s_OutOfRange;
  441. // obj.OnRecycle();
  442. // obj.name = key;
  443. // obj.transform.SetParent(PoolParent);
  444. //}
  445. //public static void DestroyPoolObject(PoolObject go, float time)
  446. //{
  447. // Timer.DelayCallBack(time, (object[] obj) =>
  448. // {
  449. // DestroyPoolObject(go);
  450. // });
  451. //}
  452. ///// <summary>
  453. ///// 清空对象池
  454. ///// </summary>
  455. //public static void CleanPool_New()
  456. //{
  457. // foreach (string name in s_objectPool_new.Keys)
  458. // {
  459. // if (s_objectPool_new.ContainsKey(name))
  460. // {
  461. // List<PoolObject> objList = s_objectPool_new[name];
  462. // for (int i = 0; i < objList.Count; i++)
  463. // {
  464. // try
  465. // {
  466. // objList[i].OnObjectDestroy();
  467. // }
  468. // catch (Exception e)
  469. // {
  470. // Debug.Log(e.ToString());
  471. // }
  472. // Destroy(objList[i].gameObject);
  473. // }
  474. // objList.Clear();
  475. // }
  476. // }
  477. // s_objectPool_new.Clear();
  478. //}
  479. ///// <summary>
  480. ///// 清除掉某一个对象的所有对象池缓存
  481. ///// </summary>
  482. //public static void CleanPoolByName_New(string name)
  483. //{
  484. // if (s_objectPool_new.ContainsKey(name))
  485. // {
  486. // List<PoolObject> objList = s_objectPool_new[name];
  487. // for (int i = 0; i < objList.Count; i++)
  488. // {
  489. // try
  490. // {
  491. // objList[i].OnObjectDestroy();
  492. // }
  493. // catch(Exception e)
  494. // {
  495. // Debug.Log(e.ToString());
  496. // }
  497. // Destroy(objList[i].gameObject);
  498. // }
  499. // objList.Clear();
  500. // s_objectPool_new.Remove(name);
  501. // }
  502. //}
  503. //#endregion
  504. //#region 新版本对象池 异步方法
  505. //public static void CreatePoolObjectAsync(string name, CallBack<PoolObject> callback, GameObject parent = null)
  506. //{
  507. // ResourceManager.LoadAsync(name, (status,res) =>
  508. // {
  509. // try
  510. // {
  511. // callback(CreatePoolObject(name, parent));
  512. // }
  513. // catch(Exception e)
  514. // {
  515. // Debug.LogError("CreatePoolObjectAsync Exception: " + e.ToString());
  516. // }
  517. // });
  518. //}
  519. //#endregion
  520. }