Files
2025-01-25 04:38:09 +08:00

89 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Thousandto.Core.Base
{
//GameObject的Cache
public class GameObjectPool
{
private static GameObjectPool _instance = null;
public static GameObjectPool Instance
{
get
{
if (_instance == null)
{
_instance = new GameObjectPool("[SimpleGameObject]");
}
return _instance;
}
}
GameObject root = null;
Transform rootTrans = null;
Queue<GameObject> _queue = new Queue<GameObject>();
//GameObject的而缓存
public GameObjectPool(string name)
{
root = new GameObject(name);
root.name = name;
rootTrans = root.transform;
rootTrans.parent = AppRoot.Transform;
}
//创建GameObject
public GameObject NewGameObject(string name)
{
GameObject result = null;
while (_queue.Count > 0 && result == null)
{
result = _queue.Dequeue();
}
if (result == null)
{
result = new GameObject();
}
else
{
if(!result.activeSelf) result.SetActive(true);
result.transform.position = Vector3.zero;
result.transform.localScale = Vector3.one;
result.transform.rotation = Quaternion.identity;
}
result.name = name;
return result;
}
//删除GameObject
public void FreeGameObject(GameObject go)
{
if (go != null && AppData.AppIsRunning)
{
//if (go.transform.childCount > 0)
//{
//Debug.LogError("GameObjectPool.FreeGameObject:好像混进来一个不得了的东西!!!>>" + UnityUtils.GetTransPath(go.transform));
//}
_queue.Enqueue(go);
go.transform.parent = root.transform;
}
}
//清理
public void Clear()
{
while (_queue.Count > 0)
{
GameObject.Destroy(_queue.Dequeue());
}
}
}
}