这节介绍一下unity中对象池的使用
public GameObject EnemyPrefab;
public static Vector3 defaultposition = new Vector3 (33,-6,8);
public GameObject[] instances;
void Start()
{
instances = new GameObject[maximnmInstanceCount]; //僵尸类数组作为对象池
for(int i = 0;i < maximnmInstanceCount;i++)
{
//使用instantiate函数实例化怪物,禁用对象并放入对象池
GameObject enemy = Instantiate (EnemyPrefab,defaultposition,Quaternion.identity) as GameObject;
EnemyPrefab.SetActive (false);
instances [i] = enemy;
}
}
//在怪物对象池中找到一个未激活enemy,找不到则返回null
private GameObject GetNextEnemy()
{
for (var i = 0; i < maximnmInstanceCount; i++)
{
if (!instances [i].activeSelf)
{
return instances [i];
}
return null;
}
}
//获取没有激活的enemy对象
private bool Generate(Vector3 position)
{
GameObject enemy = GetNextEnemy ();
if (enemy != null)
{
//激活怪物
enemy.SetActive (true);
//这里自定义函数
return true;
}
return false;
}
在日常开发中 我们激活实例化对象后 可以进行自己想要的操作
比如:初始化位置,伤害等等我们需要启用的功能
这里需要注意的一点,当怪物死亡后,我们需要有一个死亡状态处理函数。相当于把死亡的怪物放回池子里供下次使用。
对象池也有它的缺点,段时间内实例化太多的对象也会造成游戏的卡顿 ,这里我们使用协程函数以一定的时间间隔创建多个游戏对象
private int instanceCnt = 0;
void StartSpawnInstance()
{
instanceCnt = 10;
//启动协程
StartCoroutine(SpawnInstance());
}
//定义协程
IEnumerator SpawnInstance()
{
while(instanceCnt > 0)
{
//这里进行实例化游戏对象函数
instanceCnt--;
yield return new WaitForSeconds (waitTime);
}
}
下一节是渲染系统的简单优化
只是一个简单的演示 游戏cpu优化有很多的难点和有趣的地方 欢迎前辈们指导
感谢(づ ̄ 3 ̄)づ