IndieGame/client/Assets/Ether/Scripts/Module/Pool/GameObjectPool.cs

95 lines
2.1 KiB
C#
Raw Normal View History

2024-10-11 10:12:15 +08:00
/********************************************************************
: 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<GameObject> gameObjectPool = new Queue<GameObject>();
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;
}
}
}