对象池是一种Unity经常用到的内存管理服务,它的作用在于可以减少创建每个对象的系统开销。
在Unity游戏开发的过程中经常会创建一些新的对象,如果数量较少还可以接受,如果创建的新对象数量庞大,那么对内存而言是一个极大的隐患。例如射击游戏当中,每发射一颗子弹,都要创建一个新的子弹对象,那么子弹是数量庞大,可想而知一场游戏当中会创建多少这样的新对象,那么如果这些子弹创建之后都对游戏起着关键且持续性的作用也无可厚非,问题是子弹发射完成之后,几秒之后就不再拥有任何的意义,一般会将它自动的隐藏,也就是我们所说的SetActive(false),因此大量的非活跃对象出现在游戏场景当中。
为了解决大量创建重复对象造成的内存损耗,我们采用对象池的方式来解决。
具体的代码如下:
/* #########
############
#############
## ###########
### ###### #####
### ####### ####
### ########## ####
#### ########### ####
#### ########### #####
##### ### ######## #####
##### ### ######## ######
###### ### ########### ######
###### #### ############## ######
####### ##################### ######
####### ###################### ######
####### ###### ################# ######
####### ###### ###### ######### ######
####### ## ###### ###### ######
####### ###### ##### #####
###### ##### ##### ####
##### #### ##### ###
##### ### ### #
### ### ###
## ### ###
__________#_______####_______####______________
身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。
我们的未来没有BUG
* ==============================================================================
* Filename: Shoot
* Created: $time$
* Author:
* Purpose: 资源池-Object Pool技术
* ==============================================================================
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shoot : MonoBehaviour
{
public GameObject bulletPrefab;
public int bullrtCount = 30;
private List<GameObject> bulletList = new List<GameObject>();
void Start ()
{
InitButtet();
}
void InitButtet()
{
for (int i = 0; i < bullrtCount; i++)
{
GameObject go = Instantiate(bulletPrefab);
bulletList.Add(go);
go.transform.parent = transform;
go.SetActive(false);
}
}
GameObject FireBullet()
{
foreach (GameObject o in bulletList)
{
if (o.activeInHierarchy ==false)
{
o.SetActive(true);
return o;
}
}
return null;
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
// GameObject go = GameObject.Instantiate(bulletPrefab,transform.position,transform .rotation);
GameObject go = FireBullet();
go.transform.position = transform.position;
go.GetComponent<Rigidbody>().velocity = transform.forward * 25;
// Destroy(go,3);
StartCoroutine(Destroys(go));
}
}
IEnumerator Destroys(GameObject obj) {
yield return new WaitForSeconds(3);
obj.SetActive(false);
}
}
点击运行之后
创建了子弹之后