单个对象池
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class ObjectPool
{
public string Name;
[SerializeField]
private GameObject Prefab;
[SerializeField]
private int MaxCount;
private List<GameObject> PrefabList = new List<GameObject>();
public bool Contains(GameObject go)
{
return PrefabList.Contains(go);
}
public GameObject GetObject()
{
GameObject go = null;
for (int i = 0; i < PrefabList.Count; i++)
{
if (!PrefabList[i].activeSelf)
{
go = PrefabList[i];
go.SetActive(true);
break;
}
}
if (go == null)
{
if (PrefabList.Count > MaxCount)
{
GameObject.Destroy(PrefabList[0]);
PrefabList.RemoveAt(0);
}
go = GameObject.Instantiate(Prefab);
PrefabList.Add(go);
}
go.SendMessage("BeforeGetObject", SendMessageOptions.DontRequireReceiver);
return go;
}
public void HideObject(GameObject go)
{
if (PrefabList.Contains(go))
{
go.SendMessage("BeforeHideObject",SendMessageOptions.DontRequireReceiver);
go.SetActive(false);
}
}
public void HideAllObject()
{
for (int i = 0; i < PrefabList.Count; i++)
{
if (PrefabList[i].activeSelf) {
HideObject(PrefabList[i]);
}
}
}
public void InitPool()
{
PrefabList = new List<GameObject>();
}
}
管理类
using System.Collections.Generic;
using UnityEngine;
public class PoolManager
{
private static PoolManager instance;
public const string PoolConfigPath = @"Assets\Scripts\FrameWork\Pool\Resources\pool.asset";
public PoolManager()
{
ObjectPoolList objectPoolList = Resources.Load<ObjectPoolList>("pool");
foreach (var pool in objectPoolList.PoolList)
{
this.poolDict.Add(pool.Name, pool);
}
}
public static PoolManager Instance
{
get
{
if (instance == null)
{
instance = new PoolManager();
}
return instance;
}
}
private Dictionary<string, ObjectPool> poolDict = new Dictionary<string, ObjectPool>();
public GameObject GetObject(string poolName)
{
if (!poolDict.ContainsKey(poolName))
{
Debug.Log($"没有这个{poolName}池子");
return null;
}
ObjectPool pool = poolDict[poolName];
return pool.GetObject();
}
public void HideObject(GameObject go)
{
foreach (ObjectPool p in poolDict.Values)
{
if (p.Contains(go))
{
p.HideObject(go);
return;
}
}
}
public void HideAllObject(string poolName)
{
if (!poolDict.ContainsKey(poolName))
{
Debug.Log($"没有这个{poolName}池子");
}
ObjectPool pool = poolDict[poolName];
pool.HideAllObject();
}
public void InitAllPool()
{
foreach (var pool in poolDict.Values)
{
pool.InitPool();
}
}
}
using UnityEngine;
using UnityEditor;
public class PoolEditor : MonoBehaviour
{
[MenuItem("Manager/Creat PoolConfig")]
static void CreatePoolList() {
ObjectPoolList poolList = ScriptableObject.CreateInstance<ObjectPoolList>();
string path = PoolManager.PoolConfigPath;
AssetDatabase.CreateAsset(poolList,path);
AssetDatabase.SaveAssets();
EditorUtility.DisplayDialog("提示","创建成功!","好的");
}
}
using UnityEngine;
public abstract class ReuseableObject : MonoBehaviour
{
public abstract void BeforeGetObject();
public abstract void BeforeHideObject();
}