作为unity学习的小萌新,我最近学习了一下游戏对象池的写法(大佬可以跳过)
正式开始 什么是游戏游戏对象池,通俗的讲就是一个装着一堆游戏物体的容器,他是用来管理各个游戏对象的,主要是可以节省游戏对象的频繁创造和销毁所带来的性能消耗。 简单的作用就是用来提高性能的
这里我们用一个设计模式和这个游戏对象池配合使用,这就是单例模式,为什么使用他呢,因为一个游戏只能有一个游戏对象池(当然比较大型的游戏,可以有多个),所以我们用单例模式来配合使用
对象池有那些功能我们一个一个来讲述 1 池 (这里我们用Dictionary数据结构来存储) 2 创建游戏对象 (如果池里有,从池里拿,没有,则创建在池,然后再拿) 3 释放资源 (一类物体的释放) 4 回收对象(即时回收和延时回收)
我们一一实现 先来看单例抽象基类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class SingletonBase<T> : MonoBehaviour
where T : SingletonBase<T>
{
protected static T instance = null;
public static T Instance => instance;
}
主代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameObjectPool : SingletonBase<GameObjectPool>
{
Dictionary<string, List<GameObject>> pool =
new Dictionary<string, List<GameObject>>();
private GameObjectPool() { }
static GameObjectPool()
{
instance = new GameObjectPool();
}
public GameObject CreateObject(string key, GameObject go,
Vector3 position, Quaternion quaternion)
{
GameObject temogo = FindUseable(key);
if (temogo != null)
{
temogo.transform.SetPositionAndRotation(position, quaternion);
temogo.SetActive(true);
}
else
{
temogo = Instantiate(go, position, quaternion);
Add(key, temogo);
}
return temogo;
}
private void Add(string key, GameObject temogo)
{
if (!pool.ContainsKey(key))
{
pool.Add(key, new List<GameObject>());
}
pool[key].Add(temogo);
}
private GameObject FindUseable(string key)
{
if (pool.ContainsKey(key))
{
return pool[key].Find(p => !p.activeSelf);
}
return null;
}
public void Clear(string key)
{
if (pool.ContainsKey(key))
{
for (int i = 0; i < pool[key].Count; i++)
{
Destroy(pool[key][i]);
}
pool.Remove(key);
}
}
public void ClearAll()
{
foreach (var item in pool.Keys)
{
Clear(item);
}
}
public void CollectObject(GameObject go)
{
go.SetActive(false);
}
public void CollectObject(GameObject go, float delay)
{
StartCoroutine(CollectDelay(go, delay));
}
private IEnumerator CollectDelay(GameObject go, float delay)
{
yield return new WaitForSeconds(delay);
CollectObject(go);
}
}
谢谢大家观看
|