使用C#实现一个预制池
时间: 2024-02-06 07:12:43 浏览: 61
好的,这里提供一个简单的预制池实现,使用C#语言:
```csharp
using System.Collections.Generic;
using UnityEngine;
public class PrefabPool
{
private GameObject prefab;
private Transform parentTransform;
private Stack<GameObject> pool;
public PrefabPool(GameObject prefab, Transform parentTransform)
{
this.prefab = prefab;
this.parentTransform = parentTransform;
pool = new Stack<GameObject>();
}
public GameObject Get()
{
if(pool.Count == 0)
{
GameObject obj = Object.Instantiate(prefab, parentTransform);
obj.SetActive(true);
return obj;
}
else
{
GameObject obj = pool.Pop();
obj.SetActive(true);
return obj;
}
}
public void Release(GameObject obj)
{
obj.SetActive(false);
obj.transform.SetParent(parentTransform);
pool.Push(obj);
}
}
```
使用时,可以按照以下步骤:
```csharp
public class Example : MonoBehaviour
{
public GameObject prefab;
public Transform poolParentTransform;
private PrefabPool pool;
private void Start()
{
pool = new PrefabPool(prefab, poolParentTransform);
}
private void SpawnPrefab()
{
GameObject obj = pool.Get();
//使用对象
pool.Release(obj);
}
}
```
这个预制池可以在需要频繁创建和销毁预制体的场景中使用,例如游戏中的特效、UI等预制体,可以在预制体使用完毕后,将其回收到预制池中,以便下次直接从池中获取,避免频繁的创建和销毁预制体,提高性能和效率。
阅读全文