Unity3D资源池的应用
下面进行简单举例,单机右键从资源池内调用子弹
新建一个右键实例化子弹的代码挂载到相机下
public class InstanceBullet : MonoBehaviour
{
private ObjectPool objectPool;
void Start()
{
objectPool = GetComponent<ObjectPool>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = objectPool.GetBullet();
go.transform.position = this.transform.position;
go.GetComponent<Rigidbody>().velocity = transform.forward * 20;
StartCoroutine(DestoryBullet(go));
}
}
IEnumerator DestoryBullet(GameObject go)
{
yield return new WaitForSeconds(3);
go.SetActive(false);
}
}
新建一个资源池代码挂载到相机下
public class ObjectPool : MonoBehaviour
{
public GameObject BulletPrefab;
private int count = 30;
private List<GameObject> bulletList = new List<GameObject>();
private void Start()
{
InitPool();
}
void InitPool()
{
for(int i = 0; i < count; i++)
{
GameObject go = Instantiate(BulletPrefab);
bulletList.Add(go);
go.SetActive(false);
go.transform.parent =this.transform;
}
}
public GameObject GetBullet()
{
foreach(GameObject go in bulletList)
{
if (go.activeInHierarchy == false)
{
go.SetActive(true);
return go;
}
}
return null;
}
}
把做好的子弹prefab添加刚体,拖拽到脚本上,大功告成