第一个脚本,对象池,产生子弹:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletPool : MonoBehaviour {
//对象池—产生子弹
public
static BulletPool bulletPoolInstance;
//子弹池实例
public
GameObject
bulletObj;
//子弹预设体
public int
pooledAmount = 12;
//子弹池初始大小
private
List pooledGameObjects; //子弹池集合
private int
nowIndex; //当前索引号
void Awake ()
{
bulletPoolInstance = this;
//把本对象作为实例
}
void
Start()
{
pooledGameObjects = new List(); //初始化子弹池
for (int i = 0; i < pooledAmount; i++)
{
//创建子弹对象
GameObject obj =
Instantiate(bulletObj,transform.position,Quaternion.identity);
obj.SetActive(false);
//设置子弹无效
pooledGameObjects.Add(obj);
//添加到子弹池中
}
}
//获取对象池中可以使用的子弹
public
GameObject
GetPooledObject()
{
for (int i = 0; i < pooledGameObjects.Count;
i++) //把对象池遍历一遍
{
//从上一次使用过的子弹的下一个开始遍历(减少遍历次数)
int item = (nowIndex + i) % pooledGameObjects.Count;
//找到没有激活的子弹并返回
if(pooledGameObjects[item].activeInHierarchy == false)
{
nowIndex = (item + 1) % pooledGameObjects.Count;
return (GameObject)pooledGameObjects[item];
}
}
//如果遍历完子弹池发现没有可用的,执行下面
//实例化子弹,添加到子弹池中
GameObject obj = (GameObject)Instantiate(bulletObj,
transform.position, Quaternion.identity);
obj.SetActive(false);
pooledGameObjects.Add(obj);
return obj;
}
}
第二个脚本,需要时获取子弹池中的子弹:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletGet : MonoBehaviour {
public
Transform shootSpawn; //子弹发射位置
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
//获取子弹池中的子弹
GameObject bullet =
BulletPool.bulletPoolInstance.GetPooledObject();
if (bullet != null)
{
bullet.transform.position = shootSpawn.position;
bullet.SetActive(true);
}
}
}
}
第三个脚本,回收子弹:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletRecycle : MonoBehaviour {
//对象池—子弹回收
public void
OnTriggerEnter(Collider other)
{
other.gameObject.SetActive(false); //取消激活状态
}
}
加载中,请稍候......