例子1:
此例子有3个.cs文件,分别是GameObjectPool.cs,Bullet.cs,GameManager.cs
GameObjectPool.cs需要挂载到一个空物体上。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameObjectPool : MonoBehaviour
{
List<GameObject> pools = new List<GameObject>();
public static GameObjectPool _instance;
private void Awake()
{
_instance = this;
}
public GameObject MyInstantiate(GameObject name) //从对象池中取对象
{
if (pools.Count == 0)
{
return Instantiate(name, Vector3.zero, Quaternion.identity) as GameObject;
}
else
{
GameObject obj = pools[0];
obj.SetActive(true);
pools.Remove(obj);
return obj;
}
}
public void MyDisable(GameObject name) //向对象池里面存对象
{
name.SetActive(false);//将传进来的对象隐藏(处于非激活状态)
pools.Add(name);
}
}
Bullet.cs挂载到子弹对象上,并将该子弹对象设置为Prefab。
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
public static float time = 1f;//子弹等待多少时间消失
void OnEnable()
{
//脚本可用的时候,重置子弹的位置。
//如果不加这句代码,从对象池中取出的子弹就会从上一次消失的位置
//开始运动。而不是你设定的子弹生成位置
transform.position = Vector3.zero;
StartCoroutine("DelayDisable");//也可以用StartCoroutine(DelayDisable());
}
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime * 20);
}
void OnDisable()
{
Debug.Log("I'm over");
}
IEnumerator DelayDisable() //子弹消失的方法
{
yield return new WaitForSeconds(time);
GameObjectPool._instance .MyDisable(gameObject);
}
}
GameManager.cs挂载到相机上,或者新建空物体并将其挂载上去。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public GameObject mBulletPrefab;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObjectPool._instance .MyInstantiate(mBulletPrefab);
}
}
}