为了解决大量创建重复对象造成的内存损耗,我们采用对象池的方式来解决。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PoolManager : MonoBehaviour {
//单例模式,
public static PoolManager instance;
Dictionary<string, List<GameObject>> pool = new Dictionary<string, List<GameObject>>() { };//使用字典作为对象池
void Awake() {
instance = this;//单例模式
}
/// <summary>
/// 在对象池中取出物体
/// </summary>
/// <param name="go"></param>
/// <param name="position"></param>
/// <returns></returns>
public GameObject GetPoolGameObject(GameObject go,Vector3 position)
{
if (go != null)
{
string key = go.name + "(Clone)";
GameObject getGameObject;
if (pool.ContainsKey(key) && pool[key].Count > 0)//当对象池中存在要取出的物体,且数量大于0即可取出
{
getGameObject = pool[key][0];
pool[key].RemoveAt(0);
}
else if (pool.ContainsKey(key) && pool[key].Count <= 0)//当对象池中存在要取出的物体,但是数量不够时,需要实例化物体
{
getGameObject = Instantiate(go, position, Quaternion.identity) as GameObject;
}
else //当对象池中不存在物体时,需要实例化物体并将物体添加到对象池中
{
getGameObject = Instantiate(go, position, Quaternion.identity) as GameObject;
pool.Add(key, new List<GameObject>() { });
}
getGameObject.SetActive(true);
getGameObject.transform.position = position;
return getGameObject;
}
else {
return null;
}
}
/// <summary>
/// 回收物体到对象池中
/// </summary>
/// <param name="go"></param>
public void IntoPoolByGameObject(GameObject go)
{
string key = go.name + "(Clone)";
if (!pool.ContainsKey(key))
{
pool.Add(key, new List<GameObject>() { });
}
pool[key].Add(go);
go.SetActive(false);
}
}