/* Object Pool 资源池
* 在游戏开发中,子弹等的反复创建和销毁是非常消耗性能的,所以可以引入资源池技术
* 当想要创建子弹时先看池子里有没有子弹,先从池子里拿,在用完之后又自动的还到池子里
* 用资源池可以很好的节约游戏性能。
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletPool : MonoBehaviour {
public GameObject Bullet;//子弹
private int BulletCount = 30;//池子容量
List<GameObject> bulletlist = new List<GameObject>();//池子
void Start () {
Init();
}
/// <summary>
/// 初始化方法:实例化30个子弹作为子弹池子
/// </summary>
private void Init()
{
for (int i = 0; i <= BulletCount; i++)
{
GameObject go = GameObject.Instantiate(Bullet);
bulletlist.Add(go);
go.SetActive(false);
go.transform.parent = this.transform;
}
}
/// <summary>
/// 获取子弹方法
/// </summary>
/// <returns></returns>
public GameObject GetBullet()
{
foreach (GameObject go in bulletlist)
{
if (go.activeInHierarchy == false )
{
go.SetActive(true);
return go;
}
}
return null;
}
}
/*
* 使用资源池例子
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bulletfire : MonoBehaviour {
// public GameObject Bullet;
private BulletPool bulletPool;
void Start () {
bulletPool = this.GetComponent<BulletPool>();//拿到池子
}
void Update () {
if(Input .GetMouseButtonDown(0))
{
GameObject GO = bulletPool.GetBullet();//从池子中拿到子弹
GO.transform.position = transform.position;//设置子弹位置
GO.GetComponent<Rigidbody>().velocity = transform.forward * 50;//设置子弹速度
StartCoroutine(DestroyBullet(GO));//开启子弹放回池子协程
}
}
/// <summary>
/// 子弹放回池子协程
/// </summary>
/// <param name="go"></param>
/// <returns></returns>
IEnumerator DestroyBullet(GameObject go)
{
yield return new WaitForSeconds(3);
go.SetActive(false);
}
}