对象池的叫法:
软件领域:
对象池叫池,池技术,缓存,缓存技术
池也叫容器,能放多个元素的容器
对象池的定义 What,why
对象池【缓存】是提高程序性能的一种技术,
是使用空间来换取时间的技术【空间 换 性能】
对象池为什么能提高程序性能?
一般情况 程序中需要对象时,就创建,使用,
不使用的时候,从内存中清除
再次需要时,就再创建-使用- 从内存中清除
如果使用对象池:
程序中需要对象时,就创建,使用,
不使用的时候,把它返回【缓存】到对象池中,
再次需要时,就不需要再次创建,直接从池中返回使用。
从而节省了再次【再再次】创建所需要的时间,
所以整体上节省了时间,从而提高了程序的性能!
什么时候需要用到对象池:
对于项目中 频繁使用的 数量多的 对象 适合放在池里
游戏中:子弹,小怪
///<summary>
/// 游戏对象池
///<summary>
public class GameObjectPool : MonoBehaviour
{
Dictionary<string, List<GameObject>> cache = new Dictionary<string, List<GameObject>>();
public GameObject CreateObject(string key, GameObject game, Vector3 postion, Quaternion quaternion)
{
//查找对象池中有没有那个参数
GameObject temoGo = FindUsable(key);
//池中有从池中返回;池中没有加载,放入池中再返回
if (temoGo != null)
{
temoGo.transform.position = postion;
temoGo.transform.rotation = quaternion;
temoGo.SetActive(true);
}
else
{
temoGo = Instantiate(game, postion, quaternion);
Add(key, temoGo);
}
temoGo.transform.parent = transform;
return null;
}
private GameObject FindUsable(string key)
{
if (cache.ContainsKey(key))
{
return cache[key].Find(item => !item.activeSelf);
}
return null;
}
private void Add(string key, GameObject go)
{
//先检查是否有需要的key
if (!cache.ContainsKey(key))
{
cache.Add(key, new List<GameObject>());
}
cache[key].Add(go);
}
public void Clear(string key)
{
if (cache.ContainsKey(key))
{
for (int i = 0; i < cache[key].Count; i++)
{
Destroy(cache[key][i]);
}
//移除了对象的地址
cache.Remove(key);
}
}
public void ClearAll()
{
foreach ( var item in cache.Keys)
{
for (int i = 0; i < cache[item].Count; i++)
{
Destroy(cache[item][i]);
}
cache.Remove(item);
}
}
public void CollectObjiect(GameObject go)
{
go.SetActive(false);
}
//延迟回收
public void CollectObjiect(GameObject go,float delay)
{
StartCoroutine(CollectDelay( go,delay));
}
private IEnumerator CollectDelay(GameObject go,float delay)
{
yield return new WaitForSeconds(delay);
CollectObjiect(go);
}
}