您的位置:首页 > 其它

资源管理——对象池

2015-10-12 10:55 260 查看
游戏中,实例化是比较耗时的操作,在生成子弹、敌人等需要大量复制的对象时,如果都直接实例化,将增加许多没必要的内存和时间开销,因此我们应该针对这些对象使用对象池。

直接上对象池代码:

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

public class ObjectPools : MonoBehaviour
{
private GameObject result;             //对象池要返回的当前对象
private Dictionary<string, List<GameObject>> poolList;//对象池
private string keyTag;                 //对象池字典Key
private const float recycleTime = 5f;  //回收时间

#region Singleton
private static ObjectPools defautPools;
public static ObjectPools DefaultPools {
get {
return defautPools;
}
}
#endregion

void Awake()
{
poolList = new Dictionary<string, List<GameObject>>();
defautPools = this;
}

/// <summary>
/// 从对象池实例化
/// </summary>
public GameObject MyInstantiate(GameObject prefab, Vector3 position, Quaternion rotation)
{
keyTag = prefab.tag;
//如有某个小集合的Key,并且小集合内元素数量大于0
if(poolList.ContainsKey(keyTag) && poolList[keyTag].Count > 0)       //弹夹里面有子弹
{
result = (poolList[keyTag])[0];     //取弹夹里面的第一个子弹
poolList[keyTag].Remove(result);        //从弹夹里面移除子弹
result.transform.position = position;
result.transform.rotation = rotation;
}
else
{
//如果元素不存在,添加元素
if(!poolList.ContainsKey(keyTag))
{
poolList.Add(keyTag, new List<GameObject>());
}
result = (GameObject)Instantiate(prefab, position, rotation);
}
//开启回收协程方法
StartCoroutine(AutoRecycle(result));
result.SetActive(true);
return result;
}

/// <summary>
/// 协程方法回收
/// </summary>
private IEnumerator AutoRecycle(GameObject bullet)
{
yield return new WaitForSeconds(recycleTime);
poolList[bullet.tag].Add(bullet);
bullet.SetActive(false);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: