This commit is contained in:
CortexCore
2024-04-06 16:33:32 +08:00
parent 637bbef7d2
commit 37e7fcea51
42 changed files with 597 additions and 149 deletions

View File

@@ -0,0 +1,18 @@
{
"name": "BITKit.Pool",
"rootNamespace": "",
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:d525ad6bd40672747bde77962f1c401e",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 381f7acf3ae78534b99dbc017cb8e0d5
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,78 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using AYellowpaper.SerializedCollections;
using UnityEngine;
namespace BITKit
{
public class PoolService : MonoBehaviour
{
private static readonly ConcurrentDictionary<string, Transform> _Prefabs = new();
private static readonly ConcurrentDictionary<string,UnityPool<Transform>> _Pools = new();
public static Transform Get(Transform prefab)
{
_Prefabs.TryAdd(prefab.name, prefab);
var pool = _Pools.GetOrAdd(prefab.name, CreatePool);
return pool.Get();
}
public static bool TryGet(Transform prefab, out Transform instance)
{
_Prefabs.TryAdd(prefab.name, prefab);
var pool = _Pools.GetOrAdd(prefab.name, CreatePool);
instance = null;
if (pool.InstanceCount>=pool.DefaultCapacity) return false;
instance = pool.Get();
return true;
}
public static void Release(string name,Transform instance)
{
var pool = _Pools.GetOrAdd(name, CreatePool);
pool.Return(instance);
}
private static UnityPool<Transform> CreatePool(string name)
{
var pool = new UnityPool<Transform>
{
Prefab = _Prefabs[name],
OnReturn = null,
};
return pool;
}
[SerializeField] private SerializedDictionary<Transform,int> initialCapacity;
private void Start()
{
foreach (var (key, value) in initialCapacity)
{
var pool = new UnityPool<Transform>
{
Prefab = key,
DefaultCapacity = value,
Root = transform,
OnReturn = null,
};
_Prefabs.TryAdd(key.name, key);
_Pools.TryAdd(key.name, pool);
var list = new List<Transform>();
for (var i = 0; i < pool.DefaultCapacity; i++)
{
list.Add(pool.Get());
}
foreach (var x in list)
{
x.gameObject.SetActive(false);
pool.Return(x);
}
}
}
private void OnDestroy()
{
_Prefabs.Clear();
_Pools.Clear();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 74a03a9938f67ec498c7972cb0338ea6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: