使用協程創建子彈的物件池


uj5u.com熱心網友回復:
物件池不是這樣的嗎?internal sealed class ObjectPool<T>
{
List<T> pool;
int maxCount;
int boundary;
internal ObjectPool(int max)
{
pool = new List<T>(max);
maxCount = max;
boundary = 0;
}
internal bool Add(T value)
{
if (value != null && pool.Count < maxCount)
{
pool.Add(value);
boundary++;
return true;
}
return false;
}
internal T Pop()
{
lock (pool)
{
if (boundary > 0)
{
--boundary;
return pool[boundary];
}
else
{
return default(T);
}
}
}
internal void Push(T value)
{
if (value != null)
{
lock (pool)
{
int index = pool.IndexOf(value, boundary);
if (index != boundary)
{
pool[index] = pool[boundary];
pool[boundary] = value;
}
boundary++;
}
}
}
}
public class Bullet : MonoBehaviour
{
static ObjectPool<Bullet> cartridgePool;
public static void InitPool(int max)
{
cartridgePool = new ObjectPool<Bullet>(max);
for (int i = 0; i < max; i++)
{
cartridgePool.Add(Resources.Load<Bullet>("cartridge"));
}
}
public static void Launch(Transform current, Transform target)
{
var car = cartridgePool.Pop();
if (car != null)
{
car.transform.position = current.position;
car.transform.LookAt(target);
car.gameObject.SetActive(true);
}
}
private void OnEnable()
{
StartCoroutine(Timeout());
}
IEnumerator Timeout()
{
yield return new WaitForSeconds(5);
gameObject.SetActive(false);
cartridgePool.Push(this);
}
}
public class Test : MonoBehaviour
{
Transform mouseTarget;
private void Start()
{
Bullet.InitPool(100);
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Bullet.Launch(transform, mouseTarget);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/30665.html
標籤:Unity3D
