对象池的创建和使用

对象池简介

对象池用来存储需要被大量创建和重复使用的对象,降低程序的IO访问,在合适的时间点创建和释放对象池,有助于提升程序整体性能。

以下创建了一个基本的对象池,实现创建多个池,从池中取对象,回收对象,以及回收回掉。

Demo截图如下:


工程目录:


创建对象池

void Start () {
		ObjectPool.Ins.CreatePool (cubePool, () => { Debug.Log ("Create->" + cubePool.poolName + "->成功"); });
		ObjectPool.Ins.CreatePool (spherePool, () => { Debug.Log ("Create->" + spherePool.poolName + "->成功"); });
		ObjectPool.Ins.CreatePool (capsulePool, () => { Debug.Log ("Create->" + capsulePool.poolName + "->成功"); });
		ObjectPool.Ins.CreatePool (cylinderPool, () => { Debug.Log ("Create->" + cylinderPool.poolName + "->成功"); });
	}

从池中取出对象

void Update () {
		if (Input.GetKeyDown (KeyCode.A)) {
			ObjectPool.Ins.Spawn (cubePool, delegate () {
				Debug.Log ("Spawn->" + cubePool.poolName + "->成功");
			}).transform.localPosition = spawnPos;
		}
		if (Input.GetKeyDown (KeyCode.S)) {
			ObjectPool.Ins.Spawn (spherePool, delegate () {
				Debug.Log ("Spwn->" + spherePool.poolName + "->成功");
			}).transform.localPosition = spawnPos;
		}
		if (Input.GetKeyDown (KeyCode.D)) {
			ObjectPool.Ins.Spawn (capsulePool, () => {
				Debug.Log ("Spawn->" + capsulePool.poolName + "->成功");
			}).transform.localPosition = spawnPos;
		}
		if (Input.GetKeyDown (KeyCode.F)) {
			ObjectPool.Ins.Spawn (cylinderPool, () => {
				Debug.Log ("Spawn->" + cylinderPool.poolName + "->成功");
			}).transform.localPosition = spawnPos;
		}
	}

回收不使用对象

 IEnumerator RecyleObject () {
        yield return new WaitForSeconds (2);
        ObjectPool.Recyle (poolName, this.gameObject.name,RecyleAction);

    }
    //回收调用
    void RecyleAction () {
        Debug.Log ("开始回收");
        this.GetComponent<Rigidbody> ().velocity = Vector3.one;
        this.GetComponent<Rigidbody> ().angularVelocity = Vector3.zero;
        this.transform.localPosition = Vector3.zero;
        this.gameObject.SetActive (false);
    }

工程里附有详细Demo,使用时只需要将Scripts下的 ObjectPool.cs 拖动到场景中,并在代码中配置一下池要初始化的对象即可,具体看Demo.

工程地址扫码


在这里插入图片描述

地址:https://gitee.com/Sun_ME/ObjectPools.git

猜你喜欢

转载自blog.csdn.net/JianZuoGuang/article/details/84028757