对对象池的解释以及优缺点,我在这里就不多做解释了,网络上已经有很完善的解释了,总结一句话,就是我们将对象存储在一个池子中,当需要再次使用时取出,而不需要每次都实例化一个新的对象,将对象循环利用起来。
现在用一个简单的例子,来具体实现对象池。我们实现一个这样功能,按下鼠标左键,发射一颗子弹,3秒之后消失。在这个功能中,我们发射了上百上千发子弹,就需要实例化生成上百上千次。这时候,我们就需要使用对象池这个概念,每次实例化生成一个子弹对象后,三秒钟后不销毁(不执行destroy),而是将其将其隐藏(SetActive(false))并且放入对象池中。再次按下鼠标时,如果对象池不为空,就去对象池里将隐藏的对象显示出来。如果对象池里面没有可用对象时,再执行实例化子弹的方法。
- 首先创建一个对象池脚本,此脚本是一个单例脚本(不需要挂在任何游戏对象上面)。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameObjectPool : MonoBehaviour {
List<GameObject> pools = new List<GameObject> ();
private GameObjectPool(){}
private static GameObjectPool instance;
public static GameObjectPool GetInstance(){
if(instance == null){
instance = new GameObject("GameObjectPool").AddComponent<GameObjectPool>();
}
return instance;
}
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
2.创建一个名为Game Manager的脚本,来控制子弹的生成

using UnityEngine;
using System.Collections;
public class gameManager : MonoBehaviour {
public GameObject mBulletPrefab;
void Update () {
if(Input.GetMouseButtonDown(0)){
GameObjectPool.GetInstance().MyInstantiate(mBulletPrefab);
}
}
}
3.为子弹的预设体创建Bullet脚本
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
void OnEnable () {
transform.position = Vector3.zero;
StartCoroutine(DelayDisable(3f));
}
void Update () {
transform.Translate(Vector3.forward*Time.deltaTime*20);
}
void OnDisable(){
Debug.Log("I'm over");
}
IEnumerator DelayDisable(float time){
yield return new WaitForSeconds(time);
GameObjectPool.GetInstance().MyDisable(gameObject);
}
}