代码
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
static Queue<GameObject> pool = new Queue<GameObject>();
static Transform tran;
static GameObject model;
void Awake()
{
tran = transform;
model = Resources.Load("Prefab/BaseCube" ) as GameObject;
Expand();
}
static void Expand()
{
GameObject obj = null ;
for (int index = 0 ; index < 50 ; index++)
{
obj = Instantiate(model);
obj.transform.SetParent(tran);
obj.SetActive(false );
pool.Enqueue(obj);
}
}
public static GameObject GetObject ()//得到一个对象
{
if (pool.Count <= 0 )
Expand();
GameObject obj = pool.Dequeue();
obj.SetActive(true );
Debug.Log(pool.Count);
return obj;
}
public static void PushEgg (GameObject obj)//回收一个对象
{
obj.SetActive(false );
if (pool.Contains(obj))
return ;
pool.Enqueue(obj);
}
}
使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class CreateMap : MonoBehaviour
{
void Start()
{
for (int index = 0 ; index < 10 ; index++)
{
for (int count = 0 ; count < 10 ; count++)
{
GameObject game = ObjectPool.GetObject();
if ((count + index) % 2 != 0 )
game.transform.position = new Vector3(index, 0 , count);
else
ObjectPool.PushEgg(game);
}
}
}
}
结果