游戏性能优化--ObjectPool资源池的创建和使用

本文介绍了游戏开发中通过ObjectPool资源池技术优化性能的方法。利用资源池,可以避免频繁创建和销毁子弹等对象,提高游戏运行效率。示例代码展示了如何初始化和管理子弹池,以及如何在游戏逻辑中获取和回收子弹。

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

/*                   Object Pool 资源池
 *   在游戏开发中,子弹等的反复创建和销毁是非常消耗性能的,所以可以引入资源池技术
 *   当想要创建子弹时先看池子里有没有子弹,先从池子里拿,在用完之后又自动的还到池子里
 *   用资源池可以很好的节约游戏性能。
 *    
 */


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletPool : MonoBehaviour {

    public GameObject Bullet;//子弹
    private int BulletCount = 30;//池子容量
    List<GameObject> bulletlist = new List<GameObject>();//池子


	void Start () {
        Init();
	}
    /// <summary>
    /// 初始化方法:实例化30个子弹作为子弹池子
    /// </summary>
	private void Init()
    {
        for (int i = 0; i <= BulletCount; i++)
        {
            GameObject go = GameObject.Instantiate(Bullet);
            bulletlist.Add(go);
            go.SetActive(false);
            go.transform.parent = this.transform;
        }  
    }
    /// <summary>
    /// 获取子弹方法
    /// </summary>
    /// <returns></returns>
    public GameObject GetBullet()
    {
       foreach (GameObject go in bulletlist)
        {
            if (go.activeInHierarchy == false )
            {
                go.SetActive(true);
                return go;
            }
           
        }
        return null;
    }
	
	
}

/*
 *   使用资源池例子
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bulletfire : MonoBehaviour {

    // public GameObject Bullet;
    private BulletPool bulletPool;


	void Start () {
        bulletPool = this.GetComponent<BulletPool>();//拿到池子
	}

	void Update () {
		if(Input .GetMouseButtonDown(0))
        {
            GameObject GO = bulletPool.GetBullet();//从池子中拿到子弹
            GO.transform.position = transform.position;//设置子弹位置
            GO.GetComponent<Rigidbody>().velocity = transform.forward * 50;//设置子弹速度
            StartCoroutine(DestroyBullet(GO));//开启子弹放回池子协程
        }
	}
    /// <summary>
    /// 子弹放回池子协程
    /// </summary>
    /// <param name="go"></param>
    /// <returns></returns>
    IEnumerator DestroyBullet(GameObject go)
    {
        yield return new WaitForSeconds(3);
        go.SetActive(false);    
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值