咖啡丶七

自律给我自由

docker-compose.yml

1
2
3
4
5
6
7
8
9
10
11
12
services:
mongo:
image: mongo:8.0.9
container_name: mongo-wordswar
ports:
- "39090:27017"
volumes:
- ./mongo_data:/data/db
- ./log:/var/log
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: 123456
1
2
# 进入容器里的mongodb
docker exec -it <容器名称或ID> mongosh -u 用户名 -p 密码 --authenticationDatabase admin

备份指定数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
# 先备份在docker容器中
mongodump -db fantasy_main --gzip --archive=/tmp/fantasy_main.gz
# 再将其迁移出来
docker cp mongo:/tmp/fantasy_main.gz /home/ubuntu/fantasy_main.gz

# 完整命令
docker exec -it mongo-wordswar-dev mongodump -u admin -p 123456 --authenticationDatabase admin --db fantasy_main --gzip --archive=/tmp/fantasy_main_$(date +%Y%m%d_%H%M%S).gz

# 展示容器中有哪些文件
docker exec -it mongo-wordswar-dev ls -lh /tmp
-rw-r--r-- 1 root root 588K Jun 26 09:39 fantasy_main_20260626_173923.gz
# 将文件放到linux中
docker cp mongo-wordswar-dev:/tmp/fantasy_main_20260626_173923.gz .

将数据库恢复到服务器

1
2
3
4
5
6
# 先将数据放到docker容器中
docker cp fantasy_main.gz mongo:/tmp/fantasy_main.gz
# 恢复,注意:!!!!带--drop表示完全恢复到当时的状态,这段时间的修改和新创建的用户都会丢失
mongorestore --drop --gzip --archive=/tmp/fantasy_main.gz
# docker用法
docker exec -it mongo mongorestore -u admin -p 123456 --authenticationDatabase admin --drop --gzip --archive=/tmp/fantasy_main_dev_20260626_173923.gz

数据库操作

1
2
3
4
5
6
7
8
9
# 展示数据库
test> show dbs
admin 100.00 KiB
config 108.00 KiB
fantasy_main 305.12 MiB
local 72.00 KiB

# 进入数据库
use fantasy_main

集合操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 展示集合
fantasy_main> show collections
Account
ActivateUnit
MailBox
MailComponent
MailUnit

# 查看集合中的所有索引
db.Account.getIndexes()
# 输出
[ { v: 2, key: { _id: 1 }, name: '_id_' } ]

# 创建索引
db.Account.createIndex({ Openid: 1 }, { unique: true })

# 显示集合中有多少个元素
db.Account.countDocuments()

查看当前的磁盘

1
df -TH

输出

1
2
3
4
5
6
Filesystem     Type   Size  Used Avail Use% Mounted on
tmpfs tmpfs 1.7G 1.1M 1.7G 1% /run
/dev/vda2 ext4 43G 31G 11G 75% /
tmpfs tmpfs 8.2G 33k 8.2G 1% /dev/shm
tmpfs tmpfs 5.3M 0 5.3M 0% /run/lock
tmpfs tmpfs 1.7G 4.1k 1.7G 1% /run/user/1000

确认当前的磁盘

1
sudo fdisk -l

会输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 系统盘有40G
Disk /dev/vda: 40 GiB, 42949672960 bytes, 83886080 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 05ABB582-8C87-4CAF-8A44-E51F9A3A6625

Device Start End Sectors Size Type
/dev/vda1 2048 4095 2048 1M BIOS boot
/dev/vda2 4096 83886046 83881951 40G Linux filesystem

# 数据盘vdb有100GB,这个就是我们要新增的数据盘了
Disk /dev/vdb: 100 GiB, 107374182400 bytes, 209715200 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

查看磁盘系统类型

1
sudo file -s /dev/vdb

输出

1
/dev/vdb: Linux rev 1.0 ext4 filesystem data, UUID=ecd8eba2-c630-43dc-b907-438b1e5be7df (needs journal recovery) (extents) (64bit) (large files) (huge files)

可以看到 vdb 是 ext4

格式化文件系统

1
mkfs -t ext4 /dev/vdb

挂载

1
2
3
4
# 确保目标文件夹存在
mkdir /data
# 挂载
sudo mount /dev/vdb /data

确认挂载成功

1
df -TH

输出

1
2
3
4
5
6
7
8
ubuntu@VM-1-7-ubuntu:/etc$ df -TH
Filesystem Type Size Used Avail Use% Mounted on
tmpfs tmpfs 1.7G 1.2M 1.7G 1% /run
/dev/vda2 ext4 43G 31G 11G 75% /
tmpfs tmpfs 8.2G 33k 8.2G 1% /dev/shm
tmpfs tmpfs 5.3M 0 5.3M 0% /run/lock
tmpfs tmpfs 1.7G 4.1k 1.7G 1% /run/user/1000
/dev/vdb ext4 106G 7.0G 93G 7% /data

可以看到多出了一个,就说明成功了

开机自动挂载

注意:在机器重启后/data下的东西会不见,并不是他不在(使用sudo fdisk -l确认),而是没有挂载上去。这就是因为你没有设置开机自动挂载,如果你真碰到这种情况也不要害怕,重新挂载一遍就好了sudo mount /dev/vdb /data。但是千万要注意,不要格式化!!!不要格式化!!!不要格式化!!!

设置自动挂载

  1. 先备份配置文件

    1
    cp /etc/fstab /etc/fstab.bak
  2. 再将命令行写入

    1
    echo "UUID=$(sudo blkid -s UUID -o value /dev/vdb) /data ext4 defaults 0 0" | sudo tee -a /etc/fstab
  3. 确认文件正常

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    cat /etc/fstab

    ubuntu@VM-1-7-ubuntu:/etc$ cat /etc/fstab
    # /etc/fstab: static file system information.
    #
    # Use 'blkid' to print the universally unique identifier for a
    # device; this may be used with UUID= as a more robust way to name devices
    # that works even if disks are added and removed. See fstab(5).
    #
    # <file system> <mount point> <type> <options> <dump> <pass>
    # / was on /dev/vda2 during curtin installation
    /dev/disk/by-uuid/7bccaefa-b039-4ff6-bd32-22dde0066c0b / ext4 defaults 0 1
    /swapfile none swap sw 0 0
    UUID=ecd8eba2-c630-43dc-b907-438b1e5be7df /data ext4 defaults 0 0

文章原地址:Harness Engineering 深度解析:AI Agent 时代的工程范式革命

前言

在学习本篇文章前进牢记————————————你这篇文章是教你如何完全使用AI不写代码从零开发一个完整的项目,而不是简单的Vibecoding

什么是Vibeconding

Vibeconding = Vibe(氛围、感觉) + Coding(编程)。

简单说,就是跟着直觉走的编程方式:

  • 想到什么就写什么,不纠结完美的架构
  • 够用就好,不追求 100% 的测试覆盖
  • 快速迭代,边做边改
  • 保持编程的乐趣,而不是被流程和规范束缚

这听起来像是”随便写”?不完全是。

Vibecoding 的核心不是不负责任,而是在速度和质量之间找到适合当下场景的平衡点。它承认一个事实:并不是所有代码都需要完美的工程实践。

适合场景:

  • 原型开发和概念验证:你有一个想法,但不确定行不行得通,这时候需要的是快速验证,而不是完美实现,使用vibecoding可以显著缩短开发周期。
  • 个人项目和玩具项目:写着玩的项目,或者给朋友做的小工具,没必要搞得像企业级应用。享受编程的乐趣,想到什么写什么,这才是个人项目该有的样子。
  • 早期创业阶段:创业初期的主要风险之一不是代码质量,而是做错了方向。当你连用户是谁、需求是什么都不确定的时候,过度关注技术完美性就是本末倒置。与其花三个月打磨一个没人用的完美产品,不如快速迭代,根据用户反馈调整方向。等找到 Product-Market Fit 了,再回头优化也不迟。
  • 一次性脚本和工具。

不适合场景

  • 关键业务系统:支付系统、数据安全、用户隐私。这些领域容错率极地,不能“差不多就行”。
  • 多人协作的大项目:没有规范,团队会陷入混乱。
  • 长期维护的代码库:维护成本会指数级增长。(题外话:如果不是vibecoding,而是完全使用ai开发,可以让ai定期重构代码来优化)
  • 生成环境的核心功能:用户直接使用的功能,稳定性是第一位的,不能拿用户体验做实验。

Harness Engineering


Harness Engineering四大支柱

支柱一:上下文架构(Context Architecture)

核心原则:Agent应当恰好获得当前任务所需的上下文——不多不少

层级 加载时机 内容示例 上下文占用
Tier 1:会话常驻 每次会话自动加载 AGENTS.md / CLAUDE.md,项目结构概览 最小
Tier 2:按需加载 特定子 Agent 或技能被调用时 专业化 Agent 的上下文、领域知识 中等
Tier 3:持久化知识库 Agent 主动查询时 研究文档、规格说明、历史会话 按需

支柱二:Agent 专业化(Agent Specialization)

核心原则:专注于特定领域、拥有受限工具的Agent优于拥有全部权限的通用Agent。

Agent 角色 职责范围 工具权限
研究 Agent 探索代码库、分析实现细节 只读(Read, Grep, Glob)
规划 Agent 将需求分解为结构化任务 只读,无写入权限
执行 Agent 实现单个具体任务 限定范围的读写权限
审查 Agent 审计完成的工作,标记问题 只读 + 标记权限
调试 Agent 修复审查发现的问题 限定范围的修复权限
清理 Agent 对抗熵积累,清理低质量代码 读写权限

支柱三:持久化记忆(Persistent Memory)

核心原则:进度持久化在文件系统上,而非上下文窗口中。每次新Agent会话从零开始,通过文件系统制品重建上下文。

Agent的金典失败模式:

**失败模式一:试图一步到位。**Agent倾向于一次昨晚所有事情,结果在实现进行到一半时上下文窗口耗尽。下一个会话启动时看到的是半成品、没有文档的代码,只能话大量时间猜测之前发生了什么病试图恢复工作状态。

**失败模式二:过早宣布胜利。**在项目后期,当部分功能已经完成后,Agent会环顾四周,看到已有进展就直接宣布任务完成————即使还有大量功能为实现。

**失败模式三:过早标记功能完成。**在没有明确提升的情况下,Agent写完代码就标记为“完成”,缺没有做端到端测试。单元测试或curl命令通过了不代表功能真正可用。

**失败模式四:环境启动困难。**每次新会话启动时,Agent需要花费大量token弄清楚如何运行应用、如何启动开发服务器,而不是把时间花在实际开发上。

初始化Agent: 首次会话使用专门的prompt,要求模型建立初始环境——init.sh脚本、claude-progress.txt进度文件和初始git提交

编码Agent:后续每次会话要求模型在做出增量进展的同时,留下结构化更新。

每个编码Agent的典型会话启动流程如下:

  1. 运行 pwd 查看工作目录
  2. 读取 git log 和进度文件,了解最近的工作
  3. 读取 feature list 文件,选择最高优先级的未完成功能
  4. 启动开发服务器,运行基础端到端测试
  5. 确认基本功能正常后,开始新功能开发

关键发现:使用 JSON 格式追踪 feature 状态比 Markdown 更有效,因为 Agent 不太可能不恰当地修改或覆盖结构化数据。

支柱四:结构化执行(Structured Execution)

核心原则:将思考与执行分离。研究和规划在受控阶段进行,执行基于验证过的计划,验证号通过自动化反馈(测试、Linter、CI)和人类审查完毕。

结构化执行四步:

  1. 理解:探索代码库,分析需求背景,只读访问
  2. 规划:分解任务结构,指定执行计划,人类审查计划
  3. 执行:基于验证过的计划,增量实现功能,限定范围写入
  4. 验证:自动化测试反馈,Linter+CI检查,人类最终审查

人工检查点的价值:审查计划远比审查代码块。当规格正确时,实现自然可靠。当规格有误时,可以在500行代码生成之前及时纠正。


五大 Harness 原则

**原则1:设计环境,而非编写代码。**工程师的工作转向为Agent装备搞笑运行的环境。当Agent卡主时,不是“更加努力”,而是诊断“缺少什么能力”并让Agent自己构建该能力。

**原则2:机械化地执行架构约束。**不要指望 Agent “自觉遵守架构”。要把架构规则做成自动检测系统,让 Agent 一偏离就被工具拉回来。

比如你规定代码的依赖方向为Types → Config → Repo → Service → Runtime → UI,UI可以调用Runtime、Types,但是Service不能调用UI。这对AI很重要,因为AI写代码时很容易“就近解决问题”,短期看能跑,但长期会让架构变乱。原则2指的是你将这个规则记录到wiki文档中是不够的,AI不一定每次都记得,人也不一定每次都能遵守,可以使用asmdef、写一个轻量扫描器、等规则稳定后,在迁移到Roslyn Analyzer,每条规则都写“为什么错 + 怎么修 + 正确实例”。文档像交通规则,Linter/Analyzer 像护栏和测速仪。AI Agent 写得再快,只要护栏够清楚,它就不容易把车开进架构田里。

原则3:将代码仓库作为唯一实事源。所有团队知识都作为版本控制的制品放置在仓库中。

原则4:将可观测性连接到Agent。 “把AI Agent 从“只会读代码和猜结果”,升级成“能观察真实运行状态、用数据判断自己有没有修好”的工程助手。比如可以让ai查询日志和指标,检测程序的启动时长是否降低,让其做的事情变成可度量的目标。

**原则5:对抗熵。**AI 生成代码很快,但也会持续制造“杂质”;团队必须把清理机制也自动化,否则项目会越来越乱。AI写代码越多,清理工作也必须自动变多。


Harness的核心组件详解

AGENTS.md——Agent的活文档

它不是一次写完就放在哪里吃灰,而是信息项目和Agent协作过程中不断更新的文件。

什么时候该更新

1
2
3
4
5
6
7
8
Agent 反复用错 API
Agent 走错目录
Agent 把热更代码写到 Main
Agent 忘记释放资源
Agent 使用同步加载
Agent 不知道某个模块的正确入口
Agent 误跑了危险命令
Agent 总是忽略某个构建步骤

简单的错误(Agent运行了错误的命令、找到了错误的API)通过更新AGENTS.md解决。复杂的问题需要构建工具层面的解决方案。

不要维护一个巨大的 AGENTS.md,如果AGENTS.md 太长,Agent反而抓不住重点。更好的结构是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# AGENTS.md

请使用中文写提案和回答
这个文件为 Codex (Codex.ai/code) 提供指导,用于处理此代码库中的代码。
TEngine 基于 HybridCLR + YooAsset + UniTask + Luban 构建。

## 核心原则

- 异步优先:资源和 IO 使用 UniTask
- 模块访问:业务代码通过 GameModule.XXX
- 资源释放:LoadAssetAsync 对应 UnloadAsset
- 热更边界:Main 不热更,HotFix 热更
- 事件解耦:模块间用 GameEvent

## 详细文档

- 架构说明:UnityProject/repowiki/zh/content/...
- 资源管理:UnityProject/repowiki/zh/content/API参考/资源管理API.md
- UI 开发:UnityProject/repowiki/zh/content/UI系统/...

也就是AGENTS.md放最高优先级规则,细节连接放到更深的文档。

采用Tier 1/2/3 渐进式披露

Tier 1: AGENTS.md放最核心、最高频、最容易犯错的规则

Tier 2: 任务类型文档:当Agent要做具体类型的任务时再读,AGENTS.md只放链接。UnityProject\.claude\skills\tengine-dev\references\event-system.md

Tier 3: 实事源/深层文档/示例:这一层放更完整、更细、更低频的信息。UnityProject/repowiki/zh/content/API参考/资源管理API.md

由 Agent 为 Agent 维护文档:后台Agent定期做这些事情

1
2
3
4
5
检查 AGENTS.md 里的链接是否失效
检查文档里的 API 名是否和代码一致
发现旧路径、旧类名、旧规范
提交一个文档修复 PR
把最近反复出现的问题整理进 AGENTS.md

这就形成了反馈循环:

1
2
3
4
5
Agent 犯错
→ 人或工具发现
→ 更新 AGENTS.md / 文档 / Linter
→ 下次 Agent 更少犯错
→ 新问题继续沉淀

一句话总结:AGENTS.md 是 Agent 的项目驾驶手册;真正厉害的用法不是写得很长,而是让它随着错误持续变准,并把复杂规则升级成自动检查工具。

架构约束与自动化执行

分层架构依赖方向强制执行:

1
Types → Config → Repo → Service → Runtime → UI

任何违反这一方向的代码都被自定义 Linter 自动检测和阻止。在人类优先的工作流中,这些规则可能感觉过于严苛;对 Agent 来说,它们是乘数效应:一旦编码,便处处适用。

Linter错误消息即修复指令:

不仅要告诉AI错乱,还要告诉他如何修复,怎样是正确的。

结构测试:

结构测试不是测试业务功能对不对,而是测试代码结构有没有违反架构规则。比如

1
2
3
4
5
GameLogic 有没有反向污染 TEngine.Runtime?
Main 有没有引用 HotFix?
Repo 层有没有引用 UI 层?
业务代码有没有绕过 GameModule 直接访问 ModuleSystem?
资源加载有没有使用同步 API?

对 AI Agent 特别重要,是因为 Agent 经常会为了“把功能做出来”选择最短路径。比如它可能直接在某个底层模块里引用 UI 类:

1
LoginService -> LoginUI

短期能解决问题,长期就破坏架构。结构测试就是防止这种“能跑但架构坏了”的代码混进来。

可观测性集成

“把AI Agent 从“只会读代码和猜结果”,升级成“能观察真实运行状态、用数据判断自己有没有修好”的工程助手。比如:

  • 浏览器自动化:通过 Puppeter MCP 让 Agent 像人类用户一样进行端到端测试

  • Chrome DevTools 集成:Agent能捕获 DOM 快照和截图

  • 查询日志和指标查询:使性能目标(如“启动时长低于800ms”)变得可度量

  • 遥测驱动的 bug 修复:Agent利用日志、指标和Span来自主重现bug和验证修复

熵管理与“垃圾回收”

Agent生成的代码以不同于人类编写的方式积累“技术债”。OpenAI 的 Harness Engineering 报告称之为“熵”。

解决方案:定期运行的“垃圾回收” Agent:

  • 扫描文档不一致
  • 检测架构约束违规
  • 清理冗余或低质量代码
  • 确保“清理吞吐量”与“代码生成吞吐量”成比例

实践总结

行动清单

  1. 创建并维护AGENTS.md:不是一次性任务,而是每当Agent犯错时都更新的活文档。
  2. 在创库中建立单一实事源:所有团队知识作为版本控制的制品存放在代码仓库中,不放在Slack、Wiki或Google Docs。
  3. 构建自定义 Linter 并在错误消息中嵌入修复指令:工具在Agent工作时同时“教会”它。
  4. 为Agent提供端到端测试工具:浏览器自动化(如Puppeter MCP)显著提升验证质量。
  5. 实施增量执行策略:每次会话只处理一个功能,完成后提交git和进度更新。
  6. 分层管理上下文:避免将所有信息堆叠在单个文件中,使用Tier 1/2/3 渐进式披露。
  7. 上下文利用率保持在40%以下:更多token不代表更好的结构。
  8. 建立定期“垃圾回收”机制:自动化Agent定期清理技术债、检查文档一致性。

Harness成熟度评估模型

阶段 特征 工程师角色
Level 0:无 Harness 直接给 Agent prompt,无结构化约束 手动写代码+偶尔使用 AI
Level 1:基础约束 AGENTS.md + 基础 Linter + 手动测试 主要写代码,AI 辅助
Level 2:反馈回路 CI/CD 集成 + 自动化测试 + 进度追踪 规划+审查为主,部分 AI 编码
Level 3:专业化 Agent 多 Agent 角色分工 + 分层上下文 + 持久化记忆 环境设计+管理为主
Level 4:自治循环 无人值守并行化 + 自动化熵管理 + 自修复 架构师+质量把关者

关键Harness组件检查清单

组件 用途 优先级
AGENTS.md / CLAUDE.md 会话常驻上下文,动态反馈循环 P0
自定义 Linter + 结构测试 机械化执行架构约束 P0
CI/CD 管道 自动化测试和验证反馈 P0
进度文件 (progress.txt / JSON) 跨会话的持久化记忆 P1
功能列表文件 (feature_list.json) 结构化完成标准 P1
浏览器自动化 (Puppeteer MCP) 端到端测试验证 P1
可观测性集成 Agent 可查询日志/指标 P2
熵管理 Agent 定期清理低质量代码 P2
专业化子 Agent 分工协作减少上下文污染 P2
MCP 工具集成 连接外部工具和数据 P2

六大共识

共识一:瓶颈在基础设施,不在模型智能。这是整个领域最核心的共识。Can.ac 实验中仅改变 Harness 的工具格式就让 Grok Code Fast 1 从 6.7% 跳到 68.3%,LangChain 同一模型靠 Harness 改进从第 30 名跳到第 5 名。

共识二:文档必须是活的反馈循环,不是静态制品。

共识三:思考与执行必须分离。

共识四:上下文不是越多越好。

共识五:约束必须机械化执行,不能靠文档记录。

共识六:工程师角色正在从”写代码“转向”设计环境 + 管理工作“。

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

加载资源方法

加载SO文件

一般加载资源用法:

1
2
3
4
5
6
7
8
9
10
// 获取句柄
var h = GameModule.Resource.LoadAssetSyncHandle<SkillConfigHelper>(nameof(SkillConfigHelper));
// 加载句柄
await h.ToUniTask();
// 执行逻辑
_instance = h.AssetObject as SkillConfigHelper;
// 释放句柄
h.Release();
// 最好再调用一下卸载无用资源
GameModule.Resource.UnloadUnusedAssets();

如果未执行Release,会存在两个SkillConfigHelper

执行Release,但不执行UnloadUnusedAssets,其中一个引用数量会变成0

执行Release,并且执行UnloadUnusedAssets

框架内部加载资源方法

1
var h = await GameModule.Resource.LoadAssetAsync<BuffConfigHelper>(nameof(BuffConfigHelper));

如果不需要使用了,可以使用GameModule.Resource.UnloadAsset(h)释放掉,当然前提是没有任何其他对象对该SO有任何引用了。

加载GameObject

加载预制体

1
var root1 = await GameModule.Resource.LoadAssetAsync<GameObject>($"background_{levelConfig.MapImage}");

没错,就是与加载SO一样

注意:

  1. 如果再次加载,框架内部已经处理好了,不会让你多次引用句柄

  2. 如果不再使用了,需要释放掉,不然会一直存在内存中。

    1
    2
    GameModule.Resource.UnloadAsset(root1);
    GameModule.Resource.UnloadUnusedAssets();

直接生成实例

会实例化资源到场景,无需主动UnloadAsset,Destroy时自动UnloadAsset。

除了这两个,其他都必须在不再使用后释放掉。

1
2
3
4
// 同步
GameModule.Resource.LoadGameObject(assetPath);
// 异步
await GameModule.Resource.LoadGameObjectAsync(assetPath);

记录在unity中遇到的各种坑

对象销毁

GameObject被销毁后,!= null任然可能为true。比如有一个PanelBattle的类,如果你在另外一个地方存储了该类,然后又销毁了这个对象。此时如果你再访问这个对象是不会报空的(因为PanelBattle != null),但是如果你访问其中的元素就会报空(因为PanelBattle.m_btnStartButton == null)。

解决方案:在判断GameObject是否为空的时候添加一个判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 以下只是举个例子,不要这样写。
// 正常情况下,不应该直接使用GetWindow来获取其他UI实例,UI与UI之间应该使用事件来通讯。
private PanelBattle _panelBattleCache;
private PanelBattle _panelBattle
{
get
{
if (_panelBattleCache == null || _panelBattleCache.gameObject == null)
{
_panelBattleCache = GameModule.UI.GetWindow<PanelBattle>();
}

return _panelBattleCache;
}
}

案例一:

前提:你需要在物体A的下方安放子物体B,A初始化时需要获取所有的子物体B,之后物体B的数量将不再改变

触发条件:在同一帧下先回收了物体B,然后又创建了物体B,然后又初始化了A

结果:物体A使用的GetComponentsInChildren会获取到两个物体B,并且第一个B会在下一帧被回收掉,导致后续的代码会报空

解决方法:不再直接销毁掉物体B,而是使用对象池,将其回收到对象池(也就是改变了其父级),这样物体A使用GetComponentsInChildren时就只会获取到一个B

案例二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private PanelBattle _panelBattleCache;
private PanelBattle _panelBattle
{
get
{
// 这里 不仅需要判断PanelBattle == nukll,还需要判断.gameObject == null
// 因为如果PanelBattle被销毁过一次的话,_panelBattleCache一直是是被销毁但未被回收的gameObject
// 注:当PanelBattle直接继承MonoBehaviour可以不用做此操作,因为继承了MonoBehaviour的对象在判断==时会进行隐式检查
if (_panelBattleCache == null || _panelBattleCache.gameObject == null)
{
_panelBattleCache = GameModule.UI.GetWindow<PanelBattle>();
}

return _panelBattleCache;
}
}

现象

最近两天遇到了一个很奇怪的问题,在编辑器中打开ui没有问题,但是打包后出来的效果会导致ui的某些元素看不到,并且从log中能看到有很多脚本丢失的错误

然而,ui中该元素并没有什么特别的脚本,比如bg这个物体上只有Image组件

这就是一个非常离谱的问题。

解决方法

经过多次打包,最终确定打AB包时不应该使用ScriptableBuildPipline,而应该使用BuiltinBuildPipline。这样UI才能正常显示

如何设置正交相机的Size

默认 Unity 的 Orthographic 相机会根据 Size 设置竖直方向的世界高度,而宽度则是自动根据屏幕宽高比来扩展的,所以在不同的分辨率下看到的横向内容其实是不一样的

美术给过来的规格一般是720*1280,并且应该将相机的Size设置为6.4

根据正交相机的横向世界宽度计算公式为:

1
worldWidth = 2 * orthoraphicSize * (Screen.width / Screen.height)

此时worldWidth = 7.2,也就是说,在该分辨率下横向能看到 7.2 单位世界宽度

有了这个公式和worldWidth后,就可以反推其他分辨率下应该如何设置Size

如果我们希望所有分辨率下都能看到7.2单位世界宽度,那么应该使用以下公式

1
orthographicSize = worldWidth * 0.5 / (Screen.width / Screen.height)

设置动画到指定帧

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
public void SetAnimation(string _animationName, int _frame)
{
var skeletonData = skeleton.skeleton.Data;

var state = skeleton.AnimationState;
Spine.Animation animationToUse = !string.IsNullOrEmpty(_animationName) ? skeletonData.FindAnimation(_animationName) : null;
if (animationToUse != null)
{
var trackEntry = state.GetCurrent(0);
if (trackEntry == null || trackEntry.Animation.Name != _animationName || trackEntry.IsComplete && !trackEntry.Loop)
trackEntry = state.SetAnimation(0, animationToUse, false);
else
trackEntry.Loop = false;

// if (_playing)
// trackEntry.TimeScale = 1;
// else
{
trackEntry.TimeScale = 0;
trackEntry.TrackTime = Mathf.Lerp(0, trackEntry.AnimationEnd - trackEntry.AnimationStart, _frame / 100f);
}
}
else
state.ClearTrack(0);
}