对象池理解
- 主要作用: 通过重复利用已经创建的对象, 避免频繁的创建和销毁, 从而减少系统的内存分配和垃圾回收带来的消耗
- 基本原理:
- 使用某个对象时, 不直接创建, 而是去池子里取, 如果池子中有,就直接拿来用, 如果没有就创建并使用
- 不用某个对象时, 不直接销毁, 而是放回池子里
- 可以为不同种类的对象创建不同的池子
using System.Collections.Generic;
using UnityEngine;
public class MyPoolMgr
{
private MyPoolMgr() {}
private static MyPoolMgr instance;
public static MyPoolMgr Instance
{
get
{
if (instance == null)
{
instance = new MyPoolMgr();
}
return instance;
}
}
private Dictionary<string, Stack<GameObject>> poolDict = new();
public GameObject GetObj(string name)
{
GameObject obj;
if(poolDict.TryGetValue(name, out var pool))
{
if(pool.Count > 0)
{
obj = pool.Pop();
}
else
{
obj = GameObject.Instantiate(Resources.Load<GameObject>("Test/" + name));
}
}
else
{
obj = GameObject.Instantiate(Resources.Load<GameObject>("Test/" + name));
}
obj.SetActive(true);
return obj;
}
public void PushObj(string name, GameObject obj)
{
obj.SetActive(false);
if (poolDict.TryGetValue(name, out var pool))
{
pool.Push(obj);
}
else
{
var newPool = new Stack<GameObject>();
newPool.Push(obj);
poolDict.Add(name, newPool);
}
}
public void ClearPool()
{
poolDict.Clear();
}
}