咖啡丶七

自律给我自由

手机打开开发者模式,并开启usb调试

在unity中打开如下窗口,在文件管理器中打开以下路径

打开路径下的platform-tools文件夹,在cmd中进入该路径

在cmd中输入adb logcat -s Unity随后即可在cmd中实时看到log日志,这样即使程序闪退也能看到日志了

如果觉得窗口不方便查看,或者中文是乱码,可以使用adb logcat -s Unity -d > C:\Work\Project\UnityADBLog.txt将日志输出到本地文件中

引用

https://developer.aliyun.com/article/666214

扩展

在打包安卓包体时,如果出现UnityEngine.AndroidJavaException: java.lang.ClassNotFoundException,如下

1
2
3
4
01-06 10:14:03.277 9615 9656 E Unity : [TapSDK] (Main) Failed to create instance of TapSDK.Core.Mobile.TapCoreMobile: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'TapSDK.Core.BridgeAndroid' threw an exception. ---> UnityEngine.AndroidJavaException: java.lang.ClassNotFoundException: com.taptap.sdk.kit.internal.enginebridge.EngineBridge
01-06 10:14:03.277 9615 9656 E Unity : at UnityEngine.AndroidJNISafe.CheckException () [0x0008d] in /home/bokken/sharedspace/ra_2022.3/Modules/AndroidJNI/AndroidJNISafe.cs:24
01-06 10:14:03.277 9615 9656 E Unity : at UnityEngine.AndroidJNISafe.FindClass (System.String name) [0x0000c] in /home/bokken/sharedspace/ra_2022.3/Modules/AndroidJNI/AndroidJNISafe.cs:107
01-06 10:14:03.277 9615 9656 E Unity : at UnityEngine.AndroidJavaClass._AndroidJavaClass (System.String cl

可以在unity中右键Project窗口,使用以下两个方法清楚缓存并重新解析

  • Assets - External Dependency Manager - Android Resolver - Delete Resolved Libraries
  • Assets - External Dependency Manager - Android Resolver - Force Resolve

奇坑

在排除一个问题时发现的一个unity规则

此问题:无法在scene中移动A物体的子物体B,甚至连子物体的子物体C都无法移动,

​ 一开始以为是有update在改变B的Position,但是转念一想,就连物体C都无法移动,视乎有点不太合理,难道有个脚本在update中同时控制了B的坐标和C的坐标吗?

​ 但目前为止还没有其他的思路,只能先排查一下update这种情况。最后果然不出所料,并没有找到相应的代码,我甚至怀疑是不是Editor在捣鬼。

​ 但最后想通过改配置来排查问题时,偶然发现物体A的缩放居然为0,最后将其改为1之后就可以缩放了。

总结:物体的缩放为0时,会使其子物体都聚拢在父物体的原点,并且无法移动这些子物体的相对位置

TMP+Fgui坑

表现

首次打开UI时出现一帧GPU耗时超高的帧,紧接着下一帧是一帧CPU耗时超高的帧,里面具体的是Gfx,就是在等待GPU渲染完成。具体到编辑器上就是整个游戏直接卡住一会,再出现UI,到手机上更加明显。

原因

img img

这一帧GPU里有好几次TMP图集的复制操作,一次复制一个2048*2048的图集,重复十几次,导致GPU飙得很高,然后就都是同一张一模一样的图集复制好几份,不知道是要干嘛

解决

把TMP的FontAsset的设置改为1024*1024的,就直接好了,这时候TMP图集会自动分页,就好了?不知道是个什么原理

点击事件坑

部分手机型号在使用fgui时可能会丢失点击事件

原贴1

原贴2

解决方案:使用使用unity原生的Input System

官方文档:直接增加FAIRYGUI_INPUT_SYSTEM的宏即可

UI加载坑

在使用AddPackage之后,需要使用LoadAllAssets将所有的资源都加载一遍,否则在第一次打开ui时依然会卡顿一下

1
2
3
4
5
6
7
8
9
10
11
12
13
private void AddPackageAsync(byte[] data, string key)
{
UIPackage.LoadResourceAsync LoadPackageInternalAsync = async (string name, string extension, System.Type type, PackageItem item) =>
{
name = name.Replace("_fui", "");
//异步加载包关联对象
var a = await ResourceManager.instance.LoadAsset<UnityEngine.Object>(name);
//设置资源
item.owner.SetItemAsset(item, a, DestroyMethod.Unload);
};
var _package = UIPackage.AddPackage(data, key, LoadPackageInternalAsync);
_package?.LoadAllAssets();
}

创建字体

Characters.txt内容如下,其中里面可以有重复的文字,TMP在生成的时候也自会生成一份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 `~!@#$%^&*()_+-×÷=,./;'[]\<>?:"{}|· !¥…()—,。、;‘’【】《》?:“”〔〕丨丶丿乛□‰≤≥℃ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~@#$%^&*_+-=./'[]\<>"{}
获得角色
坚持时间
造成伤害
历史最高
返回
重新挑战
斗失败
攻击

暴击
英雄


增加
数量

描边

如果不同的字需要不同的描边效果,可以创建材质球,更改材质球的设置

下面提供一个效果还不错的描边设置

错误解决

1
The character used for Underline is not available in font asset [ZiYuYongSongTi-2 SDF].

当包如下警告时,说明字体里没有_下划线这个字符集,需要在创建字体的时候在Characters.txt中添加下划线。

如果已经添加了,或者使用的是动态的字体,则说明原本的ttf字体本身就没有_字符集

处理方法:

下载FontCreator软件

File->Open->打开字体

如果你不知道哪些字体中有下划线,或者你有心仪的字体的下划线,可以在随便添加一个字体后,从你指定的字体中复制一个下划线

原贴

原贴

流程

  1. 添加域名

    img img
  2. 设置证书,未设置证书的无法通过https访问

    img img
img

如上图所示,这一步骤如果没有购买腾讯的套餐可能需要手动验证域名

  1. 进入https://console.cloud.tencent.com/cns,并选择对应的解析域名,来到其记录管理界面。

  2. 添加记录

    img
  1. 域名设置

    img img img

错误排查

按照以下流程一个一个排查

  1. 如果http无法访问,检查域名管理界面的解析是否正常
  2. 如果https无法访问,检查域名管理的https配置的https服务是否开启

1. 架构设计特点

单例模式与模块化设计

  • 采用单例模式确保全局唯一的对象池管理器
  • 模块化设计,职责分离明确:
    • GameObjectPool:主管理器
    • ConfigPool:配置组对象池
    • PooledObject:池化对象封装
    • PrefabRefInfo:预制体引用计数

配置驱动架构

1
2
[CreateAssetMenu(fileName = "PoolConfig", menuName = "GameplaySystem/PoolConfig", order = 10)]
public class PoolConfigScriptableObject : ScriptableObject
  • 使用ScriptableObject配置池参数
  • 支持可视化配置管理
  • 配置与代码分离,便于调整

2. 资源管理特点

双重资源加载策略

1
2
3
4
5
public interface IResourceLoader
{
GameObject LoadPrefab(string location);
UniTask<GameObject> LoadPrefabAsync(string location, CancellationToken cancellationToken = default);
}
  • 支持Unity Resources和TEngine两种资源加载方式
  • 接口抽象,易于扩展其他资源系统
  • 同步/异步加载双重支持

智能引用计数管理

1
2
3
4
5
6
7
8
9
10
public void AddRef()
{
RefCount++;
LastAccessTime = Time.time;
}

public void RemoveRef()
{
if (RefCount > 0) RefCount--;
}
  • 防止内存泄漏的引用计数机制
  • 时间戳记录,支持过期清理
  • 防重复减少引用计数的保护机制

3. 性能优化特点

对象重用策略

1
2
3
// 重用临时队列,避免重复创建
private static Queue<PooledObject> _tempQueue = new Queue<PooledObject>();
private static readonly List<PooledObject> _expiredObjects = new List<PooledObject>();
  • 静态临时容器重用,减少GC压力
  • 队列交换技术优化内存分配
  • 过期对象批量清理机制

异步加载优化

1
2
3
4
5
6
7
8
9
if (LoadingAssets.Contains(assetPath))
{
var completionSource = new UniTaskCompletionSource<GameObject>();
if (!PendingRequests.ContainsKey(assetPath))
{
PendingRequests[assetPath] = new List<UniTaskCompletionSource<GameObject>>();
}
PendingRequests[assetPath].Add(completionSource);
}
  • 避免重复加载同一资源
  • 挂起请求队列管理
  • UniTask异步框架支持取消操作

4. 内存管理特点

分层过期清理机制

1
2
3
4
5
public void CheckExpiredObjects()
{
// 清理过期对象
CheckExpiredPrefabs(); // 清理过期预制体
}
  • 对象级别过期清理
  • 预制体级别过期清理
  • 定时清理避免内存积累

智能池容量管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (AllObjects.Count < Config.poolcnt)
{
// 创建新对象
}
else
{
// 复用最旧的非活跃对象
PooledObject oldestObj = null;
float oldestTime = float.MaxValue;
foreach (var obj in AllObjects)
{
if (!obj.isActive && obj.lastUsedTime < oldestTime)
{
oldestTime = obj.lastUsedTime;
oldestObj = obj;
}
}
}
  • LRU(最近最少使用)策略
  • 动态容量调整
  • 防止池无限增长

5. 监控与调试特点

完善的Editor扩展

1
2
[CustomEditor(typeof(GameObjectPool))]
public class GameObjectPoolEditor : UnityEditor.Editor
  • 实时监控池状态
  • 可视化进度条显示使用率
  • 详细的对象生命周期信息
  • 自动刷新机制

丰富的状态信息

1
2
3
4
5
6
public class PoolObjectInfo
{
public float remainingTime;
public float expireProgress;
public bool isActive;
}
  • 过期进度可视化
  • 剩余时间显示
  • 活跃状态监控

6. 错误处理特点

防御性编程

1
2
3
4
5
6
7
8
9
10
11
public void RemoveRef()
{
if (RefCount > 0)
{
RefCount--;
}
else
{
Log.Warning($"尝试减少已经为0的引用计数: {AssetPath}");
}
}
  • 引用计数边界检查
  • 空引用检查
  • 重复操作保护

异常恢复机制

1
2
3
4
5
6
7
8
9
while (AvailableObjects.Count > 0)
{
var obj = AvailableObjects.Dequeue();
if (obj.gameObject == null)
{
// 处理已销毁对象
continue;
}
}
  • 自动清理无效对象
  • 队列一致性维护
  • 异常状态恢复

7. 扩展性特点

接口设计

  • IResourceLoader接口支持多种资源系统
  • 配置驱动支持运行时调整
  • 事件回调机制支持自定义逻辑

生命周期管理

1
2
3
4
5
6
7
8
9
10
public class PoolObjectMonitor : MonoBehaviour
{
private void OnDestroy()
{
if (_pool != null && _pooledObject != null)
{
_pool.OnObjectDestroyed(_pooledObject);
}
}
}
  • 自动生命周期监控
  • 销毁事件处理
  • 状态同步机制

8. 使用便利性特点

简化的API设计

1
2
3
4
5
public static class GameObjectPoolHelper
{
public static GameObject LoadGameObject(string assetPath);
public static async UniTask<GameObject> LoadGameObjectAsync(string assetPath, CancellationToken cancellationToken = default);
}
  • 静态辅助类简化调用
  • 同步/异步双重接口
  • 取消令牌支持

总结

这个对象池系统展现了以下核心优势:

  1. 高性能:通过对象重用、静态容器复用、批量清理等手段最小化GC压力
  2. 高可靠性:完善的错误处理、防御性编程、状态一致性保证
  3. 高可维护性:模块化设计、配置驱动、丰富的调试信息
  4. 高扩展性:接口抽象、事件机制、生命周期管理
  5. 易用性:简化的API、详细的文档、可视化配置

整体而言,这是一个企业级的对象池实现,适用于对性能和稳定性要求较高的游戏项目。

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

/************************************************************************************************************
Class Name: GameObjectPool.cs
Type: Pool, GameObject, GameObjectPool

Example:
// 异步加载游戏物体。
var gameObject = await GameObjectPool.Instance.GetGameObjectAsync(path, token);

// 同步加载游戏物体。
var gameObject = GameObjectPool.Instance.GetGameObject(path);

Example1:
// 异步加载游戏物体。
var gameObject = await GameObjectPoolHelper.LoadGameObjectAsync(path, token);

// 同步加载游戏物体。
var gameObject = GameObjectPoolHelper.LoadGameObject(path);
************************************************************************************************************/

#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;
}

/// <summary>
/// 对象池配置项。
/// </summary>
[Serializable]
public class PoolConfig
{
public string asset;
public float time;
public int poolcnt;
}

/// <summary>
/// 预制体引用计数信息。
/// </summary>
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;
}

/// <summary>
/// 获取过期进度 (0-1),1表示即将过期。
/// </summary>
public float GetExpireProgress(float expireTime)
{
if (expireTime <= 0 || isActive) return 0f;
float timeElapsed = Time.time - lastUsedTime;
return Mathf.Clamp01(timeElapsed / expireTime);
}

/// <summary>
/// 获取剩余时间。
/// </summary>
public float GetRemainingTime(float expireTime)
{
if (expireTime <= 0 || isActive) return -1f;
float timeElapsed = Time.time - lastUsedTime;
return Mathf.Max(0f, expireTime - timeElapsed);
}
}

/// <summary>
/// Inspector显示用的对象信息。
/// </summary>
[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;
}
}

/// <summary>
/// Inspector显示用的预制体信息.
/// </summary>
[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;
}
}

/// <summary>
/// Inspector显示用的池信息。
/// </summary>
[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++;
}
}
}

/// <summary>
/// 配置组对象池 - 管理一个PoolConfig下的所有资源。
/// </summary>
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);
}

/// <summary>
/// 同步获取对象,如果资源未加载则同步加载。
/// </summary>
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);
}

/// <summary>
/// 异步获取对象。
/// </summary>
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);
}
}
}

/// <summary>
/// 对象销毁监听器。
/// </summary>
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);
}
}
}

/// <summary>
/// 游戏对象池管理器。
/// </summary>
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;
}
}

/// <summary>
/// 执行对象池清理。
/// </summary>
private void PerformCleanup()
{
if (_configPools == null || _configPools.Count == 0)
{
return;
}

foreach (var pool in _configPools)
{
pool.CheckExpiredObjects();
}
}

/// <summary>
/// 手动触发一次清理。
/// </summary>
public void ForceCleanup()
{
PerformCleanup();
_lastCleanupTime = Time.time;
}

// Editor专用的刷新。
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;
}

/// <summary>
/// 手动刷新Inspector信息
/// </summary>
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();

// 绘制默认Inspector
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布局来精确控制Foldout的大小
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;

// 使用简单的Foldout,不指定宽度
_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();

// GameObject引用
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

unity时间轮询器

unity中需要使用的轮询器的次数不多(不会达到万级别),所以一般不需要本文后面的”高性能时间轮询器”,只需要简单写一个就好了

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
#nullable enable
using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Unity专用:高性能二叉堆定时器
/// ✔ 添加 O(logN)
/// ✔ 取最早任务 O(1)
/// ✔ Tick 稳定,不会卡顿
/// ✔ GC 极低
/// ✔ 支持重复任务
/// </summary>
public sealed class TimerHeap
{
private class TimerTask
{
public ulong Id;
public float ExpireTime;
public float Interval;
public int RepeatCount;
public Action<object?>? Callback;
public object? Data;

public bool Cancelled;
}

// ---------- 堆结构(最小堆:ExpireTime 最小的在顶部) ----------
private readonly List<TimerTask> heap = new List<TimerTask>(128);

// ---------- 对象池 ----------
private readonly Stack<TimerTask> pool = new Stack<TimerTask>(128);

private ulong nextId = 0;

public ulong Schedule(Action<object?> callback, float delay, float interval = 0, int repeatCount = 0, object? data = null)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));

if (delay <= 0f) delay = 0.0001f;
if (repeatCount != 0 && interval <= 0) throw new ArgumentOutOfRangeException(nameof(interval));

float expire = Time.time + delay;

var task = AllocateTask();
task.Id = ++nextId;
task.Callback = callback;
task.Data = data;
task.Interval = interval;
task.RepeatCount = repeatCount;
task.ExpireTime = expire;
task.Cancelled = false;

Push(task);

return task.Id;
}

public bool Cancel(ulong id)
{
// 延迟删除:不从堆中立即移除
foreach (var t in heap)
{
if (t.Id == id && !t.Cancelled)
{
t.Cancelled = true;
return true;
}
}
return false;
}

/// <summary>
/// 主线程调用(在 Update 中)
/// </summary>
public void Tick()
{
float now = Time.time;

while (heap.Count > 0)
{
var t = heap[0];

// 未到时间 → break
if (t.ExpireTime > now) break;

PopTop(); // 从堆中移除该任务

if (!t.Cancelled)
{
// 执行回调
try
{
t.Callback?.Invoke(t.Data);
}
catch (Exception ex)
{
Debug.LogException(ex);
}

// 重复任务
if (t.RepeatCount != 0)
{
if (t.RepeatCount > 0) t.RepeatCount--;

t.ExpireTime = now + t.Interval;
Push(t);
continue;
}
}

// 任务结束 → 回收
ReleaseTask(t);
}
}

#region ----------- 堆操作 -----------
private void Push(TimerTask task)
{
heap.Add(task);
HeapifyUp(heap.Count - 1);
}

private void PopTop()
{
int last = heap.Count - 1;

heap[0] = heap[last];
heap.RemoveAt(last);

if (heap.Count > 0)
HeapifyDown(0);
}

private void HeapifyUp(int index)
{
var heapList = heap;

while (index > 0)
{
int parent = (index - 1) >> 1;

if (heapList[index].ExpireTime >= heapList[parent].ExpireTime)
break;

(heapList[index], heapList[parent]) = (heapList[parent], heapList[index]);
index = parent;
}
}

private void HeapifyDown(int index)
{
var heapList = heap;
int count = heapList.Count;

while (true)
{
int left = (index << 1) + 1;
if (left >= count) break;

int smallest = left;

int right = left + 1;
if (right < count && heapList[right].ExpireTime < heapList[left].ExpireTime)
{
smallest = right;
}

if (heapList[index].ExpireTime <= heapList[smallest].ExpireTime)
break;

(heapList[index], heapList[smallest]) = (heapList[smallest], heapList[index]);
index = smallest;
}
}
#endregion

#region ----------- 内存池 -----------
private TimerTask AllocateTask()
{
if (pool.Count > 0)
{
return pool.Pop();
}
return new TimerTask();
}

private void ReleaseTask(TimerTask task)
{
task.Id = 0;
task.Callback = null;
task.Data = null;

pool.Push(task);
}
#endregion
}

使用方法:

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


public sealed class LevelManager : SingletonBehaviour<LevelManager>
{
private TimerHeap _timeHeap = new TimerHeap();

private void Update()
{
_timeHeap.Tick();
}

/// <summary>
/// 添加一个以秒为单位的定时任务。
/// </summary>
/// <param name="callback">回调函数</param>
/// <param name="delay">延迟执行的秒数</param>
/// <param name="interval">重复周期的秒数 (0表示不重复)</param>
/// <param name="repeatCount">重复次数 (小于0无限, 0不重复)</param>
/// <param name="data">回调数据</param>
/// <returns>任务ID,用于取消</returns>
public ulong Schedule(Action<object?> callback, float delay, float interval = 0, int repeatCount = 0, object? data = null)
{
return _timeHeap.Schedule(callback, delay, interval, repeatCount, data);
}

/// <summary>
/// 取消一个定时任务。
/// </summary>
/// <param name="id">要取消的任务ID</param>
/// <returns>是否成功取消</returns>
public bool Cancel(ulong id)
{
if (_timeHeap == null) return false;
return _timeHeap.Cancel(id);
}
}

高性能时间轮询器

文章最后方有源码,源码的设计是通过Tick来计时的。

通过实际效果来说,就是如果将TimeWheel.SharedInstance.Tick();直接写在Unity的Update中,那么TimeWheel.SharedInstance.Schedule()的参数的单位则是Update的执行次数,而不是秒。

提高易用性

以下为我在unity中正在使用的代码。

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
using System;
using Default;
using Modules.GameManager;
using Sirenix.OdinInspector;
using UnityEngine;

public class TimeWheelDriver : MonoBehaviour
{
public float TimeScale;
private TimeWheel _timeWheel;
private double _accumulatedTimeMs = 0f;

private void Awake()
{
_timeWheel = new TimeWheel(shouldSortBeforeExecution: false);
_timeWheel.OnCallbackError += HandleCallbackError;
}

private void Update()
{
// 1. 获取自上一帧以来经过的时间(秒),并转换为毫秒
_accumulatedTimeMs += Time.deltaTime * 1000f * TimeScale;

// 2. 根据累积的毫秒数,驱动时间轮 Tick 相应次数
// 例如,如果一帧过了16.67ms,那么就 Tick 16 次,并将剩余的 0.67ms 留到下一帧
while (_accumulatedTimeMs >= 1f)
{
_timeWheel.Tick();
_accumulatedTimeMs -= 1f;
}
}

private void HandleCallbackError(Exception ex)
{
// 在Unity控制台打印错误,而不是抛出导致程序中断
Log.Error($"{Time.fixedTimeAsDouble} TimeWheel callback error: {ex}");
}
}

原作者的取消事件有问题,在取消时间时未将事件类的Next和Prev置空,现已修改,详情可看private static void RemoveTask(ref TimerTask? head, TimerTask task)方法的注释

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
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;

/// <summary>
/// Linux内核风格的分层时间轮
/// 特性:
/// 1. 五级时间轮分层
/// 2. 自动任务降级机制
/// 3. 无锁设计(基于CAS操作)
/// 4. 内存池优化
/// </summary>
public sealed class TimeWheel : IDisposable
{
#region Constants and Structs

private const int TVN_BITS = 6;
private const int TVR_BITS = 8;
private const int TVN_SIZE = 1 << TVN_BITS;
private const int TVR_SIZE = 1 << TVR_BITS;
private const int TVN_MASK = TVN_SIZE - 1;
private const int TVR_MASK = TVR_SIZE - 1;

public const long MAX_DELAY = (long)TVR_SIZE * TVN_SIZE * TVN_SIZE * TVN_SIZE * TVN_SIZE - 1;

private class TimerTask
{
public ulong Id;
public long ExecuteOrder;
public Action<object?>? Callback;
public object? Data;
public ulong ExpireTicks;
public ulong Interval;
public int RepeatCount;
public TimerTask? Next;
public TimerTask? Prev;

/// <summary>
/// 0=未激活, 1=已激活, 2=已取消
/// </summary>
public int State;
}

#endregion

#region Core Fields

private readonly TimerTask?[] tv1 = new TimerTask[TVR_SIZE];
private readonly TimerTask?[] tv2 = new TimerTask[TVN_SIZE];
private readonly TimerTask?[] tv3 = new TimerTask[TVN_SIZE];
private readonly TimerTask?[] tv4 = new TimerTask[TVN_SIZE];
private readonly TimerTask?[] tv5 = new TimerTask[TVN_SIZE];

private ulong nextId;
private long executeOrder;
private ulong currentTick;
private readonly bool shouldSortBeforeExecution;
private readonly object syncRoot = new();
private readonly Stack<TimerTask?> taskPool = new(1024);
private readonly List<TimerTask> taskListCache = new(1024);

#endregion

#region Public Interface

public static TimeWheel SharedInstance { get; private set; } = null!;

public static TimeWheel CreateSharedInstance(bool shouldSortBeforeExecution = true)
{
if (SharedInstance != null)
{
throw new Exception("SharedInstance already created");
}

return SharedInstance = new(shouldSortBeforeExecution);
}

public TimeWheel(bool shouldSortBeforeExecution = true)
{
this.shouldSortBeforeExecution = shouldSortBeforeExecution;
}

public event Action<Exception>? OnCallbackError;

/// <summary>
/// 添加定时任务
/// </summary>
/// <param name="callback">回调函数</param>
/// <param name="delay">延迟, 最小值1, 如果为0则自动设置为1</param>
/// <param name="interval">重复周期</param>
/// <param name="repeatCount">到期后, 再次重复次数(小于0无限, 0不重复)</param>
/// <param name="data">回调函数的数据————不要在callback中直接使用参数,以免发生闭包问题。将参数放在这里可以避免闭包问题</param>
/// <returns>任务句柄</returns>
public ulong Schedule(Action<object?> callback, ulong delay, ulong interval = 0, int repeatCount = 0, object? data = null)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
delay = delay switch
{
> MAX_DELAY => throw new ArgumentOutOfRangeException(nameof(delay), $"Delay must be less than {MAX_DELAY}, but got {delay}"),
0 => 1,
_ => delay
};

if (repeatCount != 0 && interval <= 0) throw new ArgumentOutOfRangeException(nameof(interval), $"Interval must be greater than zero");

var task = this.AllocateTask();
task.Id = ++this.nextId;
task.ExecuteOrder = Interlocked.Increment(ref this.executeOrder);
task.Callback = callback;
task.Data = data;
task.Interval = interval;
task.RepeatCount = repeatCount;
task.ExpireTicks = this.currentTick + delay;

lock (this.syncRoot)
{
this.InternalAddTask(task);
}

return task.Id;
}

/// <summary>
/// 取消定时任务
/// </summary>
public bool Cancel(ulong id)
{
lock (this.syncRoot)
{
foreach (var vec in new[] { this.tv1, this.tv2, this.tv3, this.tv4, this.tv5 })
{
for (int i = 0; i < vec.Length; i++)
{
TimerTask? current = vec[i];
while (current != null)
{
if (current.Id == id)
{
if (Interlocked.CompareExchange(ref current.State, 2, 1) == 1)
{
RemoveTask(ref vec[i], current);
this.ReleaseTask(current);
return true;
}

return false;
}

current = current.Next;
}
}
}

return false;
}
}

public void Dispose() { }

public void Tick()
{
lock (this.syncRoot)
{
this.TimeWheelWorker();
}
}

#endregion

#region Core Algorithm

private void TimeWheelWorker()
{
if (this.currentTick >= long.MaxValue - 1)
this.currentTick = 0;
else
this.currentTick++;

int index = (int)(this.currentTick & TVR_MASK);
if (index == 0)
{
index = (int)(this.currentTick >> TVR_BITS) & TVN_MASK;
this.CascadeTimers(this.tv2, index);
if (index == 0)
{
index = (int)((this.currentTick >> (TVR_BITS + TVN_BITS)) & TVN_MASK);
this.CascadeTimers(this.tv3, index);
if (index == 0)
{
index = (int)((this.currentTick >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK);
this.CascadeTimers(this.tv4, index);
if (index == 0)
{
index = (int)((this.currentTick >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK);
this.CascadeTimers(this.tv5, index);
}
}
}
}

this.ProcessTimers(ref this.tv1[this.currentTick & TVR_MASK]);
}

private void CascadeTimers(TimerTask?[] tv, int index)
{
TimerTask? current = tv[index];
tv[index] = null;

while (current != null)
{
TimerTask? next = current.Next;
this.InternalAddTask(current);
current = next;
}
}

private void ProcessTimers(ref TimerTask? head)
{
var taskList = this.taskListCache;
ExtractTasks(ref head, taskList);
if (taskList.Count == 0)
return;

if (taskList.Count > 1 && this.shouldSortBeforeExecution)
taskList.Sort((a, b) => a.ExecuteOrder.CompareTo(b.ExecuteOrder));

foreach (var task in taskList)
{
if (task.State == 1 && this.currentTick >= task.ExpireTicks)
{
try
{
task.Callback?.Invoke(task.Data);
}
catch (Exception ex)
{
if (this.OnCallbackError != null)
{
this.OnCallbackError.Invoke(ex);
}
else
{
throw;
}
}

if (task.RepeatCount != 0)
{
if (task.RepeatCount > 0) task.RepeatCount--;

task.ExpireTicks += task.Interval;
task.ExecuteOrder = Interlocked.Increment(ref this.executeOrder);

// 重新加入时间轮
lock (this.syncRoot)
{
this.InternalAddTask(task);
}
}
else
{
this.ReleaseTask(task);
}
}
else if (task.State == 2)
{
this.ReleaseTask(task);
}
}

taskList.Clear();
}

private static void ExtractTasks(ref TimerTask? head, List<TimerTask> taskList)
{
TimerTask? current = head;
while (current != null)
{
var next = current.Next;
taskList.Add(current);
current.Next = null;
current.Prev = null;
current = next;
}

head = null; // 清空原链表
}

private void InternalAddTask(TimerTask task)
{
// 如果任务已经被取消(State==2),则不再添加
if (Interlocked.CompareExchange(ref task.State, 1, 1) == 2)
return;

var expires = task.ExpireTicks;
var idx = expires - this.currentTick;

int i;
TimerTask?[] vec;
if (idx < TVR_SIZE)
{
i = (int)(expires & TVR_MASK);
vec = this.tv1;
}
else if (idx < (1 << (TVR_BITS + TVN_BITS)))
{
i = (int)((expires >> TVR_BITS) & TVN_MASK);
vec = this.tv2;
}
else if (idx < (1 << (TVR_BITS + 2 * TVN_BITS)))
{
i = (int)((expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK);
vec = this.tv3;
}
else if (idx < (1 << (TVR_BITS + 3 * TVN_BITS)))
{
i = (int)((expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK);
vec = this.tv4;
}
else
{
i = (int)((expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK);
vec = this.tv5;
}

// 清理指针,避免旧指向造成环
task.Prev = null;
task.Next = null;

var oldTask = vec[i];
if (oldTask != null)
{
oldTask.Prev = task;
task.Next = oldTask;
}

vec[i] = task;
// State 应设置为 1,表示激活,之前判断过 2 的情况已经返回
task.State = 1;
}

#endregion

#region Memory Management

private TimerTask AllocateTask()
{
lock (this.taskPool)
{
return this.taskPool.Count > 0 ? this.taskPool.Pop()! : new();
}
}

private void ReleaseTask(TimerTask task)
{
// 标记为已取消,避免在并发期间被重新加入
Interlocked.Exchange(ref task.State, 2);

task.Id = 0;
task.ExecuteOrder = 0;
task.Callback = null;
task.Data = null;
task.ExpireTicks = 0;
task.Interval = 0;
task.RepeatCount = 0;
task.Next = null;
task.Prev = null;
task.State = 0;

lock (this.taskPool)
{
if (this.taskPool.Count < 1024) this.taskPool.Push(task);
}
}

#endregion

#region Helpers

private static void RemoveTask(ref TimerTask? head, TimerTask task)
{
if (task.Prev != null)
task.Prev.Next = task.Next;
else
head = task.Next;

if (task.Next != null)
task.Next.Prev = task.Prev;

// 断开被移除节点的指针,避免其他线程看到旧链接
task.Next = null;
task.Prev = null;
}

#endregion
}

代码分包

  1. 搜集代码时,手机上显示fetch js,但是开发者工具上没有新增函数。

    可以使用webgl/Build/webgl.symbols.json找到对应的函数,看看有没有眼熟的函数。如果有,随便在该函数中加点什么Log

    1
    2
    3
    4
    5
    6
    "8881": "UIRVEShaderInfoAllocator_SetOpacityValue_m8A9A4001B79EDBCEA1355176EE039380E5511559", 
    "6266": "UNITY_FT_Done_Face",
    "4202": "Parser_ParseZoneAndWhitespace_m59547EAFB80879B5FE3665C0EF560945A1003A25",
    "16132": "UI::Canvas::UpdateEventIndexesRecursive\\28int&\\29",
    "11737": "TaskManager_UpdateRedDot_m225D3B6AB7C200D35300EF74A7BEE12FDEFE051E",
    "55224": "U3CU3Ec_U3CGetNetworkTimeSyncU3Eb__3_0_mEA1E7AF3786D9BAA7D1FC9E472306453AC1467B2",

    可以在TaskManager.UpdateRedDot中添加Debug.Log("更新函数,查看微信小游戏是否能识别该函数");