update
This commit is contained in:
90
Assets/WorkSpace/Review/ObjectPoolManager.cs
Normal file
90
Assets/WorkSpace/Review/ObjectPoolManager.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Pool;
|
||||
using WI;
|
||||
|
||||
namespace CHN
|
||||
{
|
||||
public class ObjectPoolManager : MonoBehaviour, ISingle
|
||||
{
|
||||
[Serializable]
|
||||
public class ObjectInfo
|
||||
{
|
||||
//public Type objectType;
|
||||
public GameObject prefab;
|
||||
public int count;
|
||||
|
||||
public ObjectInfo(GameObject item, int count)
|
||||
{
|
||||
this.prefab = item;
|
||||
this.count = count;
|
||||
}
|
||||
}
|
||||
|
||||
public List<ObjectInfo> objectInfos = new();
|
||||
HashSet<Type> cachingTypes = new();
|
||||
|
||||
Dictionary<Type, ObjectPool<Component>> cachingPools = new();
|
||||
Dictionary<Type, GameObject> prefabTable = new();
|
||||
|
||||
public T Get<T>() where T : Component
|
||||
{
|
||||
ObjectInfo targetInfo = null;
|
||||
if (!cachingTypes.Contains(typeof(T)))
|
||||
{
|
||||
foreach (var info in objectInfos)
|
||||
{
|
||||
if (!info.prefab.TryGetComponent(out T comp))
|
||||
continue;
|
||||
|
||||
prefabTable.Add(typeof(T), info.prefab);
|
||||
cachingTypes.Add(typeof(T));
|
||||
|
||||
var newPool = new ObjectPool<Component>
|
||||
(Create,
|
||||
Get,
|
||||
Release,
|
||||
Destroy, true, info.count);
|
||||
|
||||
Component Create()
|
||||
{
|
||||
var result = Instantiate(comp);
|
||||
result.GetComponent<IPooledObject>().Pool = cachingPools[typeof(T)];
|
||||
return result.GetComponent<T>();
|
||||
}
|
||||
cachingPools.Add(typeof(T), newPool);
|
||||
targetInfo = info;
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!cachingTypes.Contains(typeof(T)))
|
||||
{
|
||||
Debug.LogError($"{typeof(T)} is NOT POOL");
|
||||
return default;
|
||||
}
|
||||
|
||||
return cachingPools[typeof(T)].Get().GetComponent<T>();
|
||||
}
|
||||
|
||||
|
||||
void Get(Component comp)
|
||||
{
|
||||
comp.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
void Release(Component comp)
|
||||
{
|
||||
comp.gameObject.SetActive(false);
|
||||
comp.transform.SetParent(transform);
|
||||
}
|
||||
|
||||
void Destroy(Component comp)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user