1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
| #region Class Documentation
#endregion
using System; using System.Collections.Generic; using System.Threading; using Cysharp.Threading.Tasks; using UnityEngine; using TEngine;
#if UNITY_EDITOR using UnityEditor; #endif
namespace GameplaySystem { [CreateAssetMenu(fileName = "PoolConfig", menuName = "GameplaySystem/PoolConfig", order = 10)] public class PoolConfigScriptableObject : ScriptableObject { public List<PoolConfig> configs; }
[Serializable] public class PoolConfig { public string asset; public float time; public int poolcnt; } public class PrefabRefInfo { public GameObject Prefab; public int RefCount; public float LastAccessTime; public string AssetPath; public PrefabRefInfo(GameObject prefab, string assetPath) { this.Prefab = prefab; this.AssetPath = assetPath; this.RefCount = 0; this.LastAccessTime = Time.time; } public void AddRef() { RefCount++; LastAccessTime = Time.time; } public void RemoveRef() { if (RefCount > 0) { RefCount--; if (RefCount > 0) { LastAccessTime = Time.time; } Log.Debug($"RemoveRef: {AssetPath}, refCount: {RefCount}"); } else { Log.Warning($"尝试减少已经为0的引用计数: {AssetPath}"); } } public bool CanUnload(float expireTime) { return RefCount <= 0 && expireTime > 0 && (Time.time - LastAccessTime) > expireTime; } } [Serializable] public class PooledObject { public GameObject gameObject; public string assetPath; public float lastUsedTime; public bool isActive; public string instanceName; public bool isRefCountReduced; public PooledObject(GameObject go, string path) { gameObject = go; assetPath = path; lastUsedTime = Time.time; isActive = false; instanceName = go.name; isRefCountReduced = false; } public float GetExpireProgress(float expireTime) { if (expireTime <= 0 || isActive) return 0f; float timeElapsed = Time.time - lastUsedTime; return Mathf.Clamp01(timeElapsed / expireTime); } public float GetRemainingTime(float expireTime) { if (expireTime <= 0 || isActive) return -1f; float timeElapsed = Time.time - lastUsedTime; return Mathf.Max(0f, expireTime - timeElapsed); } } [Serializable] public class PoolObjectInfo { [SerializeField] public string objectName; [SerializeField] public string assetPath; [SerializeField] public bool isActive; [SerializeField] public float lastUsedTime; [SerializeField] public float remainingTime; [SerializeField] public float expireProgress; [SerializeField] public GameObject gameObject; public void UpdateFromPooledObject(PooledObject pooledObj, float expireTime) { objectName = pooledObj.instanceName; assetPath = pooledObj.assetPath; isActive = pooledObj.isActive; lastUsedTime = pooledObj.lastUsedTime; remainingTime = pooledObj.GetRemainingTime(expireTime); expireProgress = pooledObj.GetExpireProgress(expireTime); gameObject = pooledObj.gameObject; } } [Serializable] public class PrefabRefInfoDisplay { [SerializeField] public string assetPath; [SerializeField] public int refCount; [SerializeField] public float lastAccessTime; [SerializeField] public GameObject prefab; public void UpdateFromPrefabRefInfo(PrefabRefInfo info) { assetPath = info.AssetPath; refCount = info.RefCount; lastAccessTime = info.LastAccessTime; prefab = info.Prefab; } } [Serializable] public class ConfigPoolInfo { [SerializeField] public string configAsset; [SerializeField] public int maxCount; [SerializeField] public float expireTime; [SerializeField] public int totalObjects; [SerializeField] public int activeObjects; [SerializeField] public int availableObjects; [SerializeField] public int loadedPrefabs; [SerializeField] public List<string> assetPaths = new List<string>(); [SerializeField] public List<PoolObjectInfo> objects = new List<PoolObjectInfo>(); [SerializeField] public List<PrefabRefInfoDisplay> prefabRefs = new List<PrefabRefInfoDisplay>(); public void UpdateFromPool(ConfigPool pool) { configAsset = pool.Config.asset; maxCount = pool.Config.poolcnt; expireTime = pool.Config.time; totalObjects = pool.AllObjects.Count; activeObjects = 0; foreach (var obj in pool.AllObjects) { if (obj.isActive) activeObjects++; } availableObjects = pool.AvailableObjects.Count; loadedPrefabs = pool.LoadedPrefabs.Count; assetPaths.Clear(); assetPaths.AddRange(pool.LoadedPrefabs.Keys); objects.Clear(); int objectIndex = 0; foreach (var pooledObj in pool.AllObjects) { if (pooledObj.gameObject != null) { PoolObjectInfo info; if (objectIndex < objects.Count) { info = objects[objectIndex]; } else { info = new PoolObjectInfo(); objects.Add(info); } info.UpdateFromPooledObject(pooledObj, pool.Config.time); objectIndex++; } } prefabRefs.Clear(); int prefabIndex = 0; foreach (var kvp in pool.LoadedPrefabs) { PrefabRefInfoDisplay info; if (prefabIndex < prefabRefs.Count) { info = prefabRefs[prefabIndex]; } else { info = new PrefabRefInfoDisplay(); prefabRefs.Add(info); } info.UpdateFromPrefabRefInfo(kvp.Value); prefabIndex++; } } } public class ConfigPool { public readonly PoolConfig Config; public Queue<PooledObject> AvailableObjects; public readonly HashSet<PooledObject> AllObjects; public readonly Dictionary<string, PrefabRefInfo> LoadedPrefabs; public readonly Dictionary<string, List<UniTaskCompletionSource<GameObject>>> PendingRequests; public readonly HashSet<string> LoadingAssets; public readonly Transform PoolRoot; private readonly IResourceLoader _resourceLoader; private static Queue<PooledObject> _tempQueue = new Queue<PooledObject>(); private static readonly List<PooledObject> _expiredObjects = new List<PooledObject>(); private static readonly List<string> _expiredPrefabs = new List<string>(); public ConfigPool(PoolConfig config, IResourceLoader resourceLoader) { _resourceLoader = resourceLoader; Config = config; AvailableObjects = new Queue<PooledObject>(); AllObjects = new HashSet<PooledObject>(); LoadedPrefabs = new Dictionary<string, PrefabRefInfo>(); PendingRequests = new Dictionary<string, List<UniTaskCompletionSource<GameObject>>>(); LoadingAssets = new HashSet<string>(); GameObject poolRootGo = new GameObject($"ConfigPool_{config.asset.Replace('/', '_')}"); PoolRoot = poolRootGo.transform; PoolRoot.SetParent(GameObjectPool.Instance.poolContainer); poolRootGo.SetActive(false); } public bool MatchesAsset(string assetPath) { return assetPath.StartsWith(Config.asset); } public GameObject Get(string assetPath) { if (!LoadedPrefabs.ContainsKey(assetPath)) { if (LoadingAssets.Contains(assetPath)) { Log.Warning($"资源 {assetPath} 正在异步加载中,同步获取可能导致重复加载,建议使用异步方法"); } try { GameObject prefab = _resourceLoader.LoadPrefab(assetPath); if (prefab != null) { LoadedPrefabs[assetPath] = new PrefabRefInfo(prefab, assetPath); Log.Debug($"同步加载资源成功: {assetPath}"); } else { Log.Error($"同步加载资源失败: {assetPath}"); return null; } } catch (Exception e) { Log.Error($"同步加载资源异常: {assetPath}, 错误: {e.Message}"); return null; } } return GetInternal(assetPath); } public async UniTask<GameObject> GetAsync(string assetPath, CancellationToken cancellationToken = default) { if (LoadedPrefabs.ContainsKey(assetPath)) { return GetInternal(assetPath); } if (LoadingAssets.Contains(assetPath)) { var completionSource = new UniTaskCompletionSource<GameObject>(); if (!PendingRequests.ContainsKey(assetPath)) { PendingRequests[assetPath] = new List<UniTaskCompletionSource<GameObject>>(); } PendingRequests[assetPath].Add(completionSource); try { return await completionSource.Task.AttachExternalCancellation(cancellationToken); } catch (OperationCanceledException) { PendingRequests[assetPath].Remove(completionSource); throw; } } LoadingAssets.Add(assetPath); try { GameObject prefab = await _resourceLoader.LoadPrefabAsync(assetPath, cancellationToken); if (prefab != null) { LoadedPrefabs[assetPath] = new PrefabRefInfo(prefab, assetPath); Log.Debug($"异步加载资源成功: {assetPath}"); if (PendingRequests.ContainsKey(assetPath)) { var requests = PendingRequests[assetPath]; PendingRequests.Remove(assetPath); foreach (var request in requests) { try { var go = GetInternal(assetPath); request.TrySetResult(go); } catch (Exception e) { request.TrySetException(e); } } } return GetInternal(assetPath); } else { throw new Exception($"无法异步加载资源: {assetPath}"); } } catch (Exception e) { Log.Error($"异步加载资源失败: {assetPath}, 错误: {e.Message}"); if (PendingRequests.ContainsKey(assetPath)) { var requests = PendingRequests[assetPath]; PendingRequests.Remove(assetPath); foreach (var request in requests) { request.TrySetException(e); } } throw; } finally { LoadingAssets.Remove(assetPath); } } private GameObject GetInternal(string assetPath) { PooledObject pooledObj = null; _tempQueue.Clear(); while (AvailableObjects.Count > 0) { var obj = AvailableObjects.Dequeue(); if (obj.gameObject == null) { if (!obj.isRefCountReduced) { OnObjectReallyDestroyed(obj); } else { AllObjects.Remove(obj); } continue; } if (obj.assetPath == assetPath) { pooledObj = obj; break; } else { _tempQueue.Enqueue(obj); } } while (_tempQueue.Count > 0) { AvailableObjects.Enqueue(_tempQueue.Dequeue()); } if (pooledObj == null) { if (AllObjects.Count < Config.poolcnt) { var prefabRefInfo = LoadedPrefabs[assetPath]; GameObject instantiate = GameObject.Instantiate(prefabRefInfo.Prefab); pooledObj = new PooledObject(instantiate, assetPath); AllObjects.Add(pooledObj); prefabRefInfo.AddRef(); var monitor = instantiate.GetComponent<PoolObjectMonitor>(); if (monitor == null) { monitor = instantiate.AddComponent<PoolObjectMonitor>(); } monitor.Initialize(this, pooledObj); } else { PooledObject oldestObj = null; float oldestTime = float.MaxValue; foreach (var obj in AllObjects) { if (!obj.isActive && obj.lastUsedTime < oldestTime) { oldestTime = obj.lastUsedTime; oldestObj = obj; } } if (oldestObj != null) { DestroyPooledObject(oldestObj); var prefabRefInfo = LoadedPrefabs[assetPath]; GameObject instantiate = GameObject.Instantiate(prefabRefInfo.Prefab); pooledObj = new PooledObject(instantiate, assetPath); AllObjects.Add(pooledObj); prefabRefInfo.AddRef(); var monitor = instantiate.GetComponent<PoolObjectMonitor>(); if (monitor == null) { monitor = instantiate.AddComponent<PoolObjectMonitor>(); } monitor.Initialize(this, pooledObj); } else { Log.Warning($"对象池已满且所有对象都在使用中: {Config.asset},无法创建新对象 {assetPath}"); return null; } } } pooledObj.isActive = true; pooledObj.lastUsedTime = Time.time; pooledObj.gameObject.SetActive(true); pooledObj.gameObject.transform.SetParent(null); return pooledObj.gameObject; } public void Return(GameObject go) { PooledObject pooledObj = null; foreach (var obj in AllObjects) { if (obj.gameObject == go) { pooledObj = obj; break; } } if (pooledObj != null && pooledObj.isActive) { pooledObj.isActive = false; pooledObj.lastUsedTime = Time.time; go.SetActive(false); go.transform.SetParent(PoolRoot); go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; go.transform.localScale = Vector3.one; AvailableObjects.Enqueue(pooledObj); } } public void OnObjectDestroyed(PooledObject pooledObj) { if (!pooledObj.isRefCountReduced) { OnObjectReallyDestroyed(pooledObj); } else { AllObjects.Remove(pooledObj); CleanAvailableQueue(pooledObj); } } private void OnObjectReallyDestroyed(PooledObject pooledObj) { if (pooledObj.isRefCountReduced) { return; } pooledObj.isRefCountReduced = true; AllObjects.Remove(pooledObj); if (LoadedPrefabs.TryGetValue(pooledObj.assetPath, out PrefabRefInfo refInfo)) { refInfo.RemoveRef(); } CleanAvailableQueue(pooledObj); } private void CleanAvailableQueue(PooledObject pooledObj) { _tempQueue.Clear(); while (AvailableObjects.Count > 0) { var obj = AvailableObjects.Dequeue(); if (obj != pooledObj) { _tempQueue.Enqueue(obj); } } (AvailableObjects, _tempQueue) = (_tempQueue, AvailableObjects); } private void DestroyPooledObject(PooledObject pooledObj) { if (pooledObj.isRefCountReduced) { return; } OnObjectReallyDestroyed(pooledObj); if (pooledObj.gameObject != null) { GameObject.Destroy(pooledObj.gameObject); } } public void CheckExpiredObjects() { if (Config.time <= 0) return; float currentTime = Time.time; _expiredObjects.Clear(); foreach (var obj in AllObjects) { if (!obj.isActive && !obj.isRefCountReduced && (currentTime - obj.lastUsedTime) > Config.time) { _expiredObjects.Add(obj); } } foreach (var expiredObj in _expiredObjects) { DestroyPooledObject(expiredObj); } _tempQueue.Clear(); while (AvailableObjects.Count > 0) { var obj = AvailableObjects.Dequeue(); if (AllObjects.Contains(obj) && !obj.isRefCountReduced) { _tempQueue.Enqueue(obj); } } (AvailableObjects, _tempQueue) = (_tempQueue, AvailableObjects); CheckExpiredPrefabs(); } private void CheckExpiredPrefabs() { if (Config.time <= 0) return; _expiredPrefabs.Clear(); foreach (var kvp in LoadedPrefabs) { var refInfo = kvp.Value; if (refInfo.CanUnload(Config.time)) { _expiredPrefabs.Add(kvp.Key); } } foreach (var assetPath in _expiredPrefabs) { var refInfo = LoadedPrefabs[assetPath]; Log.Debug($"卸载过期预制体: {assetPath}, 引用计数: {refInfo.RefCount}"); _resourceLoader.UnloadAsset(refInfo.Prefab); LoadedPrefabs.Remove(assetPath); } } public void Clear() { foreach (var obj in AllObjects) { if (obj.gameObject != null) { GameObject.Destroy(obj.gameObject); } } AllObjects.Clear(); AvailableObjects.Clear(); foreach (var kvp in LoadedPrefabs) { var refInfo = kvp.Value; if (refInfo.Prefab != null) { Log.Debug($"清理时卸载预制体: {kvp.Key}, 引用计数: {refInfo.RefCount}"); _resourceLoader.UnloadAsset(refInfo.Prefab); } } LoadedPrefabs.Clear(); LoadingAssets.Clear(); foreach (var requests in PendingRequests.Values) { foreach (var request in requests) { request.TrySetCanceled(); } } PendingRequests.Clear(); if (PoolRoot != null) { GameObject.Destroy(PoolRoot.gameObject); } } } public class PoolObjectMonitor : MonoBehaviour { private ConfigPool _pool; private PooledObject _pooledObject; public void Initialize(ConfigPool pool, PooledObject pooledObject) { _pool = pool; _pooledObject = pooledObject; } private void OnDestroy() { if (_pool != null && _pooledObject != null) { _pool.OnObjectDestroyed(_pooledObject); } } } public class GameObjectPool : MonoBehaviour { private static GameObjectPool _instance; public static GameObjectPool Instance { get { if (_instance == null) { GameObject go = new GameObject("[GameObjectPool]"); _instance = go.AddComponent<GameObjectPool>(); DontDestroyOnLoad(go); } return _instance; } } [Header("检查间隔")] public float checkInterval = 10f; [Header("资源加载器")] public bool useEngineResourceLoader = true; [Header("Inspector显示设置")] public bool showDetailedInfo = true; [Header("池状态信息")] [SerializeField] private List<ConfigPoolInfo> poolInfos = new List<ConfigPoolInfo>(); public Transform poolContainer; internal IResourceLoader _resourceLoader; private List<PoolConfig> _poolConfigs; private List<ConfigPool> _configPools; private Dictionary<GameObject, ConfigPool> _gameObjectToPool; private static readonly List<GameObject> _preloadedObjects = new List<GameObject>(); private float _lastCleanupTime; private void Awake() { if (_instance == null) { _instance = this; DontDestroyOnLoad(gameObject); Initialize(); } else if (_instance != this) { Destroy(gameObject); } } private void Initialize() { _resourceLoader = useEngineResourceLoader ? new TEngineResourceLoader() as IResourceLoader : new DefaultResourceLoader() as IResourceLoader; GameObject containerGo = new GameObject("PoolContainer"); poolContainer = containerGo.transform; poolContainer.SetParent(transform); _configPools = new List<ConfigPool>(); _gameObjectToPool = new Dictionary<GameObject, ConfigPool>(); try { _poolConfigs = ModuleSystem.GetModule<IResourceModule>().LoadAsset<PoolConfigScriptableObject>("PoolConfig").configs; _poolConfigs.Sort((a, b) => b.asset.Length.CompareTo(a.asset.Length)); foreach (var config in _poolConfigs) { var configPool = new ConfigPool(config, _resourceLoader); _configPools.Add(configPool); } } catch (Exception e) { Log.Error($"加载对象池配置失败: {e.Message}"); _poolConfigs = new List<PoolConfig>(); } _lastCleanupTime = Time.time; } private void Update() { if (Time.time - _lastCleanupTime >= checkInterval) { PerformCleanup(); _lastCleanupTime = Time.time; } } private void PerformCleanup() { if (_configPools == null || _configPools.Count == 0) { return; } foreach (var pool in _configPools) { pool.CheckExpiredObjects(); } } public void ForceCleanup() { PerformCleanup(); _lastCleanupTime = Time.time; } private void UpdateInspectorInfo() { poolInfos.Clear(); foreach (var pool in _configPools) { var info = new ConfigPoolInfo(); info.UpdateFromPool(pool); poolInfos.Add(info); } } public void SetResourceLoader(IResourceLoader resourceLoader) { _resourceLoader = resourceLoader; } public GameObject GetGameObject(string assetPath) { ConfigPool pool = FindConfigPool(assetPath); GameObject go = null; if (pool != null) { go = pool.Get(assetPath); } else { go = _resourceLoader.LoadGameObject(assetPath); } if (go != null && pool != null) { _gameObjectToPool[go] = pool; } return go; } public async UniTask<GameObject> GetGameObjectAsync(string assetPath, CancellationToken cancellationToken = default) { ConfigPool pool = FindConfigPool(assetPath); GameObject go = null; if (pool != null) { go = await pool.GetAsync(assetPath, cancellationToken); } else { go = await _resourceLoader.LoadGameObjectAsync(assetPath, null, cancellationToken); } if (go != null && pool != null) { _gameObjectToPool[go] = pool; } return go; } public void Release(GameObject go) { if (go == null) return; if (_gameObjectToPool.TryGetValue(go, out ConfigPool pool)) { pool.Return(go); _gameObjectToPool.Remove(go); } else { Destroy(go); } } public async UniTask PreloadAsync(string assetPath, int count = 1, CancellationToken cancellationToken = default) { ConfigPool pool = FindConfigPool(assetPath); if (pool == null) { Log.Warning($"资源 {assetPath} 没有对应的池配置,无法预加载"); return; } _preloadedObjects.Clear(); for (int i = 0; i < count; i++) { GameObject go = await pool.GetAsync(assetPath, cancellationToken); if (go != null) { _preloadedObjects.Add(go); } } foreach (var go in _preloadedObjects) { pool.Return(go); _gameObjectToPool.Remove(go); } } public void Preload(string assetPath, int count = 1) { ConfigPool pool = FindConfigPool(assetPath); if (pool == null) { Log.Warning($"资源 {assetPath} 没有对应的池配置,无法预加载"); return; } _preloadedObjects.Clear(); for (int i = 0; i < count; i++) { GameObject go = pool.Get(assetPath); if (go != null) { _preloadedObjects.Add(go); } } foreach (var go in _preloadedObjects) { pool.Return(go); _gameObjectToPool.Remove(go); } } private ConfigPool FindConfigPool(string assetPath) { foreach (var pool in _configPools) { if (pool.MatchesAsset(assetPath)) { return pool; } } return null; } public void RefreshInspectorInfo() { UpdateInspectorInfo(); } public void ClearAllPools() { foreach (var pool in _configPools) { pool.Clear(); } _gameObjectToPool.Clear(); poolInfos.Clear(); } private void OnDestroy() { ClearAllPools(); } } public interface IResourceLoader { GameObject LoadPrefab(string location); UniTask<GameObject> LoadPrefabAsync(string location, CancellationToken cancellationToken = default); GameObject LoadGameObject(string location, Transform parent = null); UniTask<GameObject> LoadGameObjectAsync(string location, Transform parent = null, CancellationToken cancellationToken = default); void UnloadAsset(GameObject gameObject); } public class DefaultResourceLoader : IResourceLoader { public GameObject LoadPrefab(string location) { return Resources.Load<GameObject>(location); } public async UniTask<GameObject> LoadPrefabAsync(string location, CancellationToken cancellationToken = default) { return await Resources.LoadAsync<GameObject>(location).ToUniTask(cancellationToken: cancellationToken) as GameObject; } public GameObject LoadGameObject(string location, Transform parent = null) { var prefab = Resources.Load<GameObject>(location); if (prefab == null) return null; var instance = GameObject.Instantiate(prefab); if (instance != null && parent != null) { instance.transform.SetParent(parent); } return instance; } public async UniTask<GameObject> LoadGameObjectAsync(string location, Transform parent = null, CancellationToken cancellationToken = default) { var prefab = await Resources.LoadAsync<GameObject>(location).ToUniTask(cancellationToken: cancellationToken) as GameObject; if (prefab == null) return null; var instance = GameObject.Instantiate(prefab); if (instance != null && parent != null) { instance.transform.SetParent(parent); } return instance; } public void UnloadAsset(GameObject gameObject) { Resources.UnloadAsset(gameObject); } } public class TEngineResourceLoader : IResourceLoader { private IResourceModule _resourceModule; private void CheckInit() { if (_resourceModule == null) { _resourceModule = ModuleSystem.GetModule<IResourceModule>(); } } public GameObject LoadPrefab(string location) { CheckInit(); return _resourceModule.LoadAsset<GameObject>(location); } public async UniTask<GameObject> LoadPrefabAsync(string location, CancellationToken cancellationToken = default) { CheckInit(); return await _resourceModule.LoadAssetAsync<GameObject>(location, cancellationToken); } public GameObject LoadGameObject(string location, Transform parent = null) { CheckInit(); return _resourceModule.LoadGameObject(location, parent); } public async UniTask<GameObject> LoadGameObjectAsync(string location, Transform parent = null, CancellationToken cancellationToken = default) { CheckInit(); return await _resourceModule.LoadGameObjectAsync(location, parent, cancellationToken); } public void UnloadAsset(GameObject gameObject) { CheckInit(); _resourceModule.UnloadAsset(gameObject); } } public static class GameObjectPoolHelper { public static GameObject LoadGameObject(string assetPath) { return GameObjectPool.Instance.GetGameObject(assetPath); } public static async UniTask<GameObject> LoadGameObjectAsync(string assetPath, CancellationToken cancellationToken = default) { return await GameObjectPool.Instance.GetGameObjectAsync(assetPath, cancellationToken); } public static void Release(GameObject go) { GameObjectPool.Instance.Release(go); } } }
#if UNITY_EDITOR namespace GameplaySystem { [CustomEditor(typeof(GameObjectPool))] public class GameObjectPoolEditor : UnityEditor.Editor { private bool[] _poolFoldouts; private bool[] _prefabFoldouts; private float _lastRefreshTime; private const float AUTO_REFRESH_INTERVAL = 0.1f;
private SerializedProperty _poolInfosProperty; private void OnEnable() { _poolInfosProperty = serializedObject.FindProperty("poolInfos"); _lastRefreshTime = Time.time; } public override void OnInspectorGUI() { var pool = (GameObjectPool)target; serializedObject.Update(); DrawDefaultInspector(); EditorGUILayout.Space(); if (GUILayout.Button("刷新池状态信息")) { RefreshPoolInfo(pool); } bool shouldAutoRefresh = pool.showDetailedInfo && Selection.activeGameObject == pool.gameObject && Time.time - _lastRefreshTime > AUTO_REFRESH_INTERVAL; if (shouldAutoRefresh) { RefreshPoolInfo(pool); } if (!pool.showDetailedInfo) { serializedObject.ApplyModifiedProperties(); return; } EditorGUILayout.Space(); EditorGUILayout.LabelField("对象池详细信息", EditorStyles.boldLabel); _poolInfosProperty = serializedObject.FindProperty("poolInfos"); if (_poolInfosProperty != null && _poolInfosProperty.arraySize > 0) { DrawPoolInfos(); } else { EditorGUILayout.HelpBox("暂无池信息,请等待系统初始化或点击刷新按钮", MessageType.Info); } if (Selection.activeGameObject == pool.gameObject) { EditorGUILayout.HelpBox("Inspector正在自动刷新 (仅在选中时)", MessageType.Info); } serializedObject.ApplyModifiedProperties(); } private void RefreshPoolInfo(GameObjectPool pool) { pool.RefreshInspectorInfo(); _lastRefreshTime = Time.time; serializedObject.Update(); if (Selection.activeGameObject == pool.gameObject) { EditorUtility.SetDirty(pool); Repaint(); } } private void DrawPoolInfos() { int poolCount = _poolInfosProperty.arraySize; if (_poolFoldouts == null || _poolFoldouts.Length != poolCount) { bool[] oldPoolFoldouts = _poolFoldouts; bool[] oldPrefabFoldouts = _prefabFoldouts; _poolFoldouts = new bool[poolCount]; _prefabFoldouts = new bool[poolCount]; if (oldPoolFoldouts != null) { for (int i = 0; i < Mathf.Min(oldPoolFoldouts.Length, poolCount); i++) { _poolFoldouts[i] = oldPoolFoldouts[i]; if (oldPrefabFoldouts != null && i < oldPrefabFoldouts.Length) { _prefabFoldouts[i] = oldPrefabFoldouts[i]; } } } } for (int i = 0; i < poolCount; i++) { DrawPoolInfo(i); } } private void DrawPoolInfo(int poolIndex) { var poolInfo = _poolInfosProperty.GetArrayElementAtIndex(poolIndex); if (poolInfo == null) return; var configAssetProp = poolInfo.FindPropertyRelative("configAsset"); var totalObjectsProp = poolInfo.FindPropertyRelative("totalObjects"); var maxCountProp = poolInfo.FindPropertyRelative("maxCount"); var activeObjectsProp = poolInfo.FindPropertyRelative("activeObjects"); if (configAssetProp == null || totalObjectsProp == null || maxCountProp == null || activeObjectsProp == null) return; string configAsset = configAssetProp.stringValue; int totalObjects = totalObjectsProp.intValue; int maxCount = maxCountProp.intValue; int activeObjects = activeObjectsProp.intValue; EditorGUILayout.BeginVertical("box"); Rect rect = EditorGUILayout.GetControlRect(); Rect foldoutRect = new Rect(rect.x, rect.y, 15, rect.height); Rect progressRect = new Rect(rect.x + 20, rect.y, rect.width - 120, rect.height); Rect labelRect = new Rect(rect.x + rect.width - 95, rect.y, 95, rect.height); _poolFoldouts[poolIndex] = EditorGUI.Foldout(foldoutRect, _poolFoldouts[poolIndex], GUIContent.none); float usage = maxCount > 0 ? (float)totalObjects / maxCount : 0f; EditorGUI.ProgressBar(progressRect, usage, $"{configAsset} ({totalObjects}/{maxCount})"); EditorGUI.LabelField(labelRect, $"活跃:{activeObjects}", EditorStyles.miniLabel); if (_poolFoldouts[poolIndex]) { EditorGUI.indentLevel++; DrawPoolDetails(poolInfo, poolIndex); EditorGUI.indentLevel--; } EditorGUILayout.EndVertical(); EditorGUILayout.Space(); } private void DrawPoolDetails(SerializedProperty poolInfo, int poolIndex) { var configAssetProp = poolInfo.FindPropertyRelative("configAsset"); var maxCountProp = poolInfo.FindPropertyRelative("maxCount"); var expireTimeProp = poolInfo.FindPropertyRelative("expireTime"); var loadedPrefabsProp = poolInfo.FindPropertyRelative("loadedPrefabs"); if (configAssetProp != null) EditorGUILayout.LabelField($"配置路径: {configAssetProp.stringValue}"); if (maxCountProp != null) EditorGUILayout.LabelField($"最大数量: {maxCountProp.intValue}"); if (expireTimeProp != null) EditorGUILayout.LabelField($"过期时间: {expireTimeProp.floatValue}s"); if (loadedPrefabsProp != null) EditorGUILayout.LabelField($"已加载预制体: {loadedPrefabsProp.intValue}"); EditorGUILayout.Space(); DrawPrefabRefs(poolInfo, poolIndex); DrawObjectDetails(poolInfo); } private void DrawPrefabRefs(SerializedProperty poolInfo, int poolIndex) { var prefabRefsProp = poolInfo.FindPropertyRelative("prefabRefs"); if (prefabRefsProp == null || prefabRefsProp.arraySize <= 0) return; _prefabFoldouts[poolIndex] = EditorGUILayout.Foldout(_prefabFoldouts[poolIndex], "预制体引用信息:"); if (_prefabFoldouts[poolIndex]) { EditorGUI.indentLevel++; for (int j = 0; j < prefabRefsProp.arraySize; j++) { DrawPrefabRefInfo(prefabRefsProp.GetArrayElementAtIndex(j)); } EditorGUI.indentLevel--; } EditorGUILayout.Space(); } private void DrawPrefabRefInfo(SerializedProperty prefabRef) { if (prefabRef == null) return; var assetPathProp = prefabRef.FindPropertyRelative("assetPath"); var refCountProp = prefabRef.FindPropertyRelative("refCount"); var lastAccessTimeProp = prefabRef.FindPropertyRelative("lastAccessTime"); var prefabObjProp = prefabRef.FindPropertyRelative("prefab"); EditorGUILayout.BeginHorizontal("box"); EditorGUILayout.BeginVertical(); if (assetPathProp != null) EditorGUILayout.LabelField($"{System.IO.Path.GetFileName(assetPathProp.stringValue)}", EditorStyles.boldLabel); if (refCountProp != null) EditorGUILayout.LabelField($"引用计数: {refCountProp.intValue}", EditorStyles.miniLabel); if (lastAccessTimeProp != null) EditorGUILayout.LabelField($"最后访问: {(Time.time - lastAccessTimeProp.floatValue):F1}秒前", EditorStyles.miniLabel); EditorGUILayout.EndVertical(); if (prefabObjProp != null) EditorGUILayout.ObjectField(prefabObjProp.objectReferenceValue, typeof(GameObject), false, GUILayout.Width(100)); EditorGUILayout.EndHorizontal(); } private void DrawObjectDetails(SerializedProperty poolInfo) { var objectsProp = poolInfo.FindPropertyRelative("objects"); if (objectsProp == null || objectsProp.arraySize <= 0) return; EditorGUILayout.LabelField("对象详情:", EditorStyles.boldLabel); for (int j = 0; j < objectsProp.arraySize; j++) { DrawObjectInfo(objectsProp.GetArrayElementAtIndex(j)); } } private void DrawObjectInfo(SerializedProperty obj) { if (obj == null) return; var objNameProp = obj.FindPropertyRelative("objectName"); var objAssetPathProp = obj.FindPropertyRelative("assetPath"); var isActiveProp = obj.FindPropertyRelative("isActive"); var remainingTimeProp = obj.FindPropertyRelative("remainingTime"); var expireProgressProp = obj.FindPropertyRelative("expireProgress"); var gameObjectProp = obj.FindPropertyRelative("gameObject"); EditorGUILayout.BeginHorizontal("box"); bool isActive = isActiveProp?.boolValue ?? false; var statusColor = isActive ? Color.green : Color.yellow; var prevColor = GUI.color; GUI.color = statusColor; EditorGUILayout.LabelField("●", GUILayout.Width(15)); GUI.color = prevColor; EditorGUILayout.BeginVertical(); string objName = objNameProp?.stringValue ?? "Unknown"; string objAssetPath = objAssetPathProp?.stringValue ?? ""; EditorGUILayout.LabelField($"{objName} ({System.IO.Path.GetFileName(objAssetPath)})", EditorStyles.boldLabel); EditorGUILayout.LabelField($"状态: {(isActive ? "活跃" : "空闲")}", EditorStyles.miniLabel); if (!isActive && remainingTimeProp != null && expireProgressProp != null) { float remainingTime = remainingTimeProp.floatValue; float expireProgress = expireProgressProp.floatValue; if (remainingTime >= 0) { Rect expireRect = GUILayoutUtility.GetRect(100, 16, GUILayout.ExpandWidth(true), GUILayout.Height(16)); EditorGUI.ProgressBar(expireRect, expireProgress, $"释放倒计时: {remainingTime:F1}s"); } } EditorGUILayout.EndVertical(); if (gameObjectProp != null) EditorGUILayout.ObjectField(gameObjectProp.objectReferenceValue, typeof(GameObject), true, GUILayout.Width(100)); EditorGUILayout.EndHorizontal(); } public override bool RequiresConstantRepaint() { var pool = target as GameObjectPool; return pool != null && pool.showDetailedInfo && Selection.activeGameObject == pool.gameObject; } } } #endif
|