一、对象池原理
1.一般对象动态创建----生命周期到了则消失。
【消耗CPU:需要不断给对象申请内存空间,最后释放。】
2.对象池:将对象存入对象池,需要时读取(OnSpawn),不需要时放入(OnUnspawn),则可以重复利用,减少频繁创建对象与删除对象的消耗。
? ? ? ? ? ? ? ? ?
二、结构
1、IReusable接口:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IReusable
{
//当取出时调用
void OnSpawn();
//当回收时调用
void OnUnspawn();
}
2、ReusableObject类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ReusableObject : MonoBehaviour, IReusable
{
public abstract void OnSpawn();
public abstract void OnUnspawn();
}
3、SubPool类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SubPool
{
//预设
GameObject moban_prefab;
//集合
List<GameObject> moban_object = new List<GameObject>();
//名字(只读)
public string Name
{
get {return moban_prefab.name;}
}
//构造
public SubPool(GameObject prefab)
{
this.moban_prefab = prefab;
}
//取对象
public GameObject Spawn()
{
GameObject go = null;
foreach (GameObject obj in moban_object)
{
if (!obj.activeSelf)
{
go = obj;
break;
}
}
//在池子中没找到对象,则创建一个
if (go == null)
{
go = GameObject.Instantiate<GameObject>(moban_prefab);
moban_object.Add(go);
}
go.SetActive(true);
go.SendMessage("OnSpawn", SendMessageOptions.DontRequireReceiver);
return go;
}
//回收对象
public void Unspawn(GameObject go)
{
if (Contains(go))
{
go.SendMessage("OnUnspawn", SendMessageOptions.DontRequireReceiver);
go.SetActive(false);
}
}
//回收该池子的所有对象
public void UnspawnAll()
{
foreach(GameObject item in moban_object)
{
//判断目前是否为可用状态
if (item.activeSelf)
{
Unspawn(item);
}
}
}
//判断是否在池子
public bool Contains(GameObject go)
{
return moban_object.Contains(go);
}
}
4、ObjectPool类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : Singleton<ObjectPool>
{
public string ResourceDir = "";
Dictionary<string, SubPool> moban_pools = new Dictionary<string, SubPool>();
//取对象
public GameObject Spawn(string name)
{
if (!moban_pools.ContainsKey(name))
{
RegisterNew(name);
}
SubPool pool = moban_pools[name];
return pool.Spawn();
}
//回收对象
public void Unspawn(GameObject go)
{
SubPool pool = null;
foreach (SubPool p in moban_pools.Values)
{
if (p.Contains(go))
{
pool = p;
break;
}
}
pool.Unspawn(go);
}
//回收所有对象
public void UnspawnAll()
{
foreach (SubPool p in moban_pools.Values)
{
p.UnspawnAll();
}
}
//创建新子池子
private void RegisterNew(string name)
{
//预设路径
string path = "";
if (string.IsNullOrEmpty(ResourceDir))//资源目录是否存在
path = name;
else
path = ResourceDir + "/" + name;
//加载预设
GameObject prefab = Resources.Load<GameObject>(path);
//创建子对象池
SubPool pool = new SubPool(prefab);
moban_pools.Add(pool.Name, pool);
}
}
|