对象池的创建和使用

本文深入介绍了对象池技术,一种用于存储大量重复使用对象的方法,旨在减少程序的IO访问,提高整体性能。通过创建和管理对象池,可以在适当的时间点创建和回收对象,包括立方体、球体、胶囊和圆柱等几何对象,附带详细Demo。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对象池简介

对象池用来存储需要被大量创建和重复使用的对象,降低程序的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值