对象池在游戏优化中起着很重要的作用,今天我们来实现一个简单的对象池功能。
1.打开Unity,创建3个C#脚本,分别为GameController.cs(游戏控制器),ObjectPool.cs(对象池),CubeMgr.cs(延迟销毁物体),代码分别如下:
GameController.cs用于游戏的控制器,点击鼠标左键,生成Cube。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameController : MonoBehaviour { public static GameController _instance; //cube预设体 public GameObject cubePrefab; //对象池 public ObjectPool op; void Awake(){ _instance = this; } // Use this for initialization void Start () { op = new ObjectPool (cubePrefab, 3); } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { GameObject go = op.GetInstance(); StartCoroutine( go.GetComponent<CubeMgr> ().DelayTime ()); } } }
ObjectPool.cs用于管理生成的所有的游戏对象。
using UnityEngine; using System.Collections.Generic; public class ObjectPool{ //要生成的对象池预设 private GameObject prefab; //对象池列表 private List<GameObject> pool; //构造函数 public ObjectPool(GameObject prefab, int initialSize) { this.prefab = prefab; this.pool = new List<GameObject>(); for (int i = 0; i < initialSize; i++) { AlllocateInstance(); } } /// <summary> /// 获取实例 /// </summary> public GameObject GetInstance() { if (pool.Count == 0) { AlllocateInstance(); } GameObject instance = pool[0]; pool.RemoveAt(0); instance.SetActive(true); return InitInstance (instance); } /// <summary> /// 初始化实例 /// </summary> protected virtual GameObject InitInstance(GameObject instance){ instance.transform.position = new Vector3 (Random.Range (-5f, 5f), Random.Range (-5f, 5f), Random.Range (-5f, 5f)); Debug.Log ("初始化实例"); return instance; } //protected virtual void /// <summary> /// 释放实例 /// </summary> public void ReleaseInstance(GameObject instance) { instance.SetActive(false); pool.Add(RevokeInstance (instance)); } /// <summary> /// 撤销实例 /// </summary> protected virtual GameObject RevokeInstance(GameObject instance){ Debug.Log ("撤销实例"); return instance; } /// <summary> /// 生成本地实例 /// </summary> private GameObject AlllocateInstance() { GameObject instance = (GameObject) GameObject.Instantiate(prefab); instance.SetActive(false); pool.Add(instance); return GenerateInstance (instance); } /// <summary> /// 创建实例 /// </summary> protected GameObject GenerateInstance(GameObject instance){ Debug.Log ("创建实例"); return instance; } }
CubeMgr.cs用于物体的延迟销毁。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CubeMgr : MonoBehaviour { public IEnumerator DelayTime() { yield return new WaitForSeconds(3f); GameController._instance.op.ReleaseInstance(this.gameObject); } }
2.如图创建游戏对象:
3.运行游戏,点击鼠标左键,即可看到有物体生成。如图: