对象池模式

using System.Threading;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
public GameObject objectToPool;
public List thePool = new List();
public int maxNum = 30;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < maxNum; i++)
{
thePool.Add(Instantiate(objectToPool));
thePool[i].transform.parent=this.transform;
thePool[i].SetActive(false);
}
}

///
/// 如果要生成多个预制体,使用对象池可以增强性能
/// 使用对象池在游戏加载时就生成一定数量的预制体,在游戏中不需要在次生成,提高性能
///
///
///
///
public GameObject SpawnObject(Vector3 pos,Quaternion rot)
{
GameObject toReturn;
if (thePool.Count > 0)
{
toReturn = thePool[0];
thePool.RemoveAt(0);
}
else
{ // 防止对象池中设置的数量不够造成报错
toReturn = Instantiate(objectToPool);
toReturn.transform.parent = this.transform;
}

    toReturn.SetActive(true);
    toReturn.transform.position = pos;      //  设置位置
    toReturn.transform.rotation = rot;      //  设置旋转
    return toReturn;
}

///
/// 游戏物体需要销毁时,回到对象池中
///
///
public void objectBack(GameObject againToPool)
{
thePool.Add(againToPool);
againToPool.SetActive(false);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值