Files
UnityAI/modules/frameworks/内存对象管理/使用指南.md
lms ee1ff7f444 [docs][refactor]: 将旧 01~06 中文教程合并整理为 modules/frameworks 文件夹结构
- 删除 01~05 旧中文教程目录
- 将 03 核心功能教程拆分为各 framework 模块的子文档
- 06 工具脚本移入 modules/frameworks/编辑器工具/UI工具/
- 非框架内容合并进 rules/20-开发规则.md 与 rules/40-工作流清单.md
- 更新所有交叉链接与文档关联表

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 18:36:15 +08:00

117 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 对象池使用指南
## 一、GameObject 对象池
### 1.1 基本用法
```csharp
public class BulletManager : MonoBehaviour
{
[SerializeField] private GameObject bulletPrefab;
private HFObjectMemPool m_BulletPool;
void Awake()
{
// 创建对象池
m_BulletPool = new HFObjectMemPool(bulletPrefab, transform);
}
public void Fire(Vector3 position, Quaternion rotation)
{
bool isNew;
GameObject bullet = m_BulletPool.GetItem(out isNew);
bullet.transform.position = position;
bullet.transform.rotation = rotation;
// 如果是新创建的对象,初始化组件
if (isNew)
{
bullet.GetComponent<BulletComponent>().Initialize();
}
}
public void RecycleBullet(GameObject bullet)
{
m_BulletPool.GiveBack(bullet);
}
void OnDestroy()
{
// 清理对象池
m_BulletPool.Recycle();
}
}
```
---
## 二、脚本对象池
### 2.1 基本用法
```csharp
public class EventArgPool : MonoBehaviour
{
private HFScriptMemPool<GameEventArgs> m_ArgPool;
void Awake()
{
m_ArgPool = new HFScriptMemPool<GameEventArgs>();
}
public GameEventArgs GetEventArgs(GameEventId eventId)
{
bool isNew;
GameEventArgs arg = m_ArgPool.GetItem(out isNew);
arg.eventId = eventId;
return arg;
}
public void RecycleEventArgs(GameEventArgs arg)
{
m_ArgPool.GiveBack(arg);
}
}
```
---
## 三、使用注意事项
### 3.1 对象池设计特点
| 特性 | 说明 |
|-----|------|
| **双池结构** | 空闲池 + 使用池,高效管理对象状态 |
| **内存泄漏检测** | 归还时校验来源,及时发现问题 |
| **泛型支持** | `HFScriptMemPool<T>` 提供类型安全 |
| **Mono 支持** | 自动创建 GameObject无缝集成 Unity |
### 3.2 性能优化建议
- 频繁创建销毁的对象必须使用对象池
- 合理设置对象池初始容量
- 定期清理空闲对象避免内存泄漏
---
**版本**: v1.0
**生效日期**: 2026年
**适用范围**: GiftGameX 项目业务开发人员
---
## 文档关联
> 当本文档发生变更时,应同步检查以下关联文档,避免信息不一致。
| 文档 | 关联原因 |
|---|---|
| [对象池与运行时对象管理入口](README.md) | 本文件是内存对象管理模块的子文档 |
| [实体系统](../实体系统/README.md) | 实体池是对象池的一种特化 |
| [资源管理](../资源管理/README.md) | RT 对象资源加载依赖资源管理 |
| [modules/模块索引.md](../../模块索引.md) | 模块索引是项目知识总入口 |
| [rules/10-架构说明.md](../../../rules/10-架构说明.md) | 架构说明定义总体分层和依赖方向 |
| [rules/30-模块登记规则.md](../../../rules/30-模块登记规则.md) | 模块登记规则定义分类和状态口径 |