/******************************************************************** 文件: GameObjectPool.cs 作者: 梦语 邮箱: 1982614048@qq.com 创建时间: 2024/03/29 17:28:19 最后修改: 梦语 最后修改时间: 2024/04/12 17:55:05 功能: 预制体对象池 *********************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Ether { public class GameObjectPool { private GameObject root; private Queue gameObjectPool = new Queue(); public GameObjectPool(string name, GameObject poolRoot) { root = new GameObject(name); root.transform.SetParent(poolRoot.transform); } public void Push(GameObject go) { gameObjectPool.Enqueue(go); go.transform.SetParent(root.transform); go.SetActive(false); } public GameObject Get(string assetName, Transform parent = null) { GameObject go; if (gameObjectPool.Count > 0) { go = gameObjectPool.Dequeue(); } else { go = LoaderTools.LoadGameObjectAndInstantiateAsync(assetName, parent); } if (parent == null) { // 回归默认场景 UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(go, UnityEngine.SceneManagement.SceneManager.GetActiveScene()); } else { go.transform.SetParent(parent); go.transform.localPosition = Vector3.zero; } go.SetActive(true); return go; } public GameObject Get(GameObject assetGo, Transform parent = null) { string assetName = assetGo.name; GameObject go; if (gameObjectPool.Count > 0) { go = gameObjectPool.Dequeue(); } else { go = LoaderTools.Instantiate(assetGo, parent); } if (parent == null) { // 回归默认场景 UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(go, UnityEngine.SceneManagement.SceneManager.GetActiveScene()); } else { go.transform.SetParent(parent); go.transform.localPosition = Vector3.zero; } go.SetActive(true); return go; } public int GetCount() { return gameObjectPool.Count; } } }