using System. Collections. Generic;
using UnityEngine;
public class BulletsPool : MonoBehaviour
{
public static BulletsPool bulletsPoolInstance;
public GameObject bulletObj;
public int pooledAmount = 5 ;
public bool lockPoolSize = false ;
private List< GameObject> pooledObjects;
private int currentIndex = 0 ;
void Awake ( )
{
bulletsPoolInstance = this ;
}
void Start ( )
{
pooledObjects = new List < GameObject > ( ) ;
for ( int i = 0 ; i < pooledAmount; ++ i)
{
GameObject obj = Instantiate ( bulletObj) ;
obj. SetActive ( false ) ;
pooledObjects. Add ( obj) ;
}
}
public GameObject GetPooledObject ( )
{
for ( int i = 0 ; i < pooledObjects. Count; ++ i)
{
int temI = ( currentIndex + i) % pooledObjects. Count;
if ( ! pooledObjects[ temI] . activeInHierarchy)
{
currentIndex = ( temI + 1 ) % pooledObjects. Count;
return pooledObjects[ temI] ;
}
}
if ( ! lockPoolSize)
{
GameObject obj = Instantiate ( bulletObj) ;
pooledObjects. Add ( obj) ;
return obj;
}
return null ;
}
}
```csharp
using UnityEngine;
public class AutoFire : MonoBehaviour
{
//传统创建子弹方法需要的子弹perfabs
//public GameObject shotObj;
public GameObject shotSpawn; //子弹发射的初始化位置
public float fireRate = 0.2f; //每次发射子弹事件间隔
private float nextFire; //下一次发射子弹的时间
void Update()
{
if (Time.time > nextFire) //可以发射子弹时间
{
nextFire = Time.time + fireRate;
//传统创建子弹方法
//Instantiate(shotObj, shotSpawn.transform.position, shotSpawn.transform.rotation);
//获取对象池中的子弹
GameObject bullet = BulletsPool.bulletsPoolInstance.GetPooledObject();
if (bullet != null) //不为空时执行
{
bullet.SetActive(true); //
if (bullet.GetComponent<MoveSpeed>()==null)
{
bullet.AddComponent<MoveSpeed>();
}
bullet.transform.position = shotSpawn.transform.position;
}
}
}
}