Files
tracy-for-unity/unity_examples/QUICKSTART.md
2025-11-26 14:35:58 +08:00

495 lines
10 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.

# Tracy Unity 集成快速开始指南
本指南将帮助你快速将 Tracy 性能分析器集成到 Unity 项目中。
---
## 🚀 快速开始5 分钟集成)
### 步骤 1: 准备 Tracy
1. 克隆或下载 Tracy 仓库:
```bash
git clone https://github.com/wolfpld/tracy.git
```
2. (可选)编译 Tracy Profiler 工具:
```bash
cd tracy/profiler
# Windows: 使用 Visual Studio 打开并编译
# macOS/Linux:
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build
```
### 步骤 2: 编译 Unity Plugin
#### Windows (使用 CMake + Visual Studio)
```powershell
# 在 unity_examples 目录下
mkdir build
cd build
# 配置(修改 TRACY_ROOT 路径指向你的 tracy 目录)
cmake .. -G "Visual Studio 17 2022" -A x64 ^
-DTRACY_ROOT="D:/path/to/tracy" ^
-DTRACY_ENABLE=ON ^
-DTRACY_ON_DEMAND=ON
# 编译
cmake --build . --config Release
```
编译完成后DLL 文件在 `build/Unity/Plugins/x86_64/UnityTracyPlugin.dll`
#### macOS
```bash
# 在 unity_examples 目录下
mkdir build && cd build
# 配置
cmake .. \
-DCMAKE_BUILD_TYPE=Release \
-DTRACY_ROOT="/path/to/tracy" \
-DTRACY_ENABLE=ON \
-DTRACY_ON_DEMAND=ON
# 编译
make -j8
```
编译完成后,动态库在 `build/Unity/Plugins/macOS/UnityTracyPlugin.dylib`
#### Linux
```bash
# 在 unity_examples 目录下
mkdir build && cd build
# 配置
cmake .. \
-DCMAKE_BUILD_TYPE=Release \
-DTRACY_ROOT="/path/to/tracy" \
-DTRACY_ENABLE=ON \
-DTRACY_ON_DEMAND=ON
# 编译
make -j8
```
编译完成后,动态库在 `build/Unity/Plugins/Linux/x86_64/UnityTracyPlugin.so`
### 步骤 3: 集成到 Unity 项目
1. **复制 Plugin 文件**
将编译好的 Plugin 复制到 Unity 项目:
```
YourUnityProject/
└── Assets/
└── Plugins/
├── x86_64/
│ └── UnityTracyPlugin.dll # Windows
├── macOS/
│ └── UnityTracyPlugin.dylib # macOS
└── Linux/
└── x86_64/
└── UnityTracyPlugin.so # Linux
```
2. **复制 C# 脚本**
将以下文件复制到 Unity 项目:
```
YourUnityProject/
└── Assets/
└── Scripts/
└── Tracy/
├── TracyWrapper.cs # Tracy C# API
├── TracyManager.cs # Tracy 管理器
└── TracyExamples.cs # 使用示例(可选)
```
3. **配置 Plugin 导入设置**
在 Unity Editor 中:
- 选择 `UnityTracyPlugin.dll`(或 .dylib/.so
- 在 Inspector 中设置平台:
- Windows: 勾选 `x86_64`
- macOS: 勾选 `macOS`
- Linux: 勾选 `Linux x86_64`
### 步骤 4: 在场景中使用
1. **添加 TracyManager**
在你的主场景中:
- 创建空 GameObject命名为 "TracyManager"
- 添加 `TracyManager` 组件
- 在 Inspector 中配置选项
2. **在代码中使用 Tracy**
```csharp
using UnityEngine;
using TracyProfiler;
public class MyGameScript : MonoBehaviour
{
void Update()
{
// 方式 1: 使用 using 语句(推荐)
using (Tracy.Zone("MyGameScript.Update"))
{
DoSomething();
}
// 方式 2: 手动开始/结束
Tracy.BeginZone("CustomZone");
DoSomethingElse();
Tracy.EndZone();
// 绘制数值
Tracy.Plot("Enemy Count", enemyCount);
// 发送消息
if (playerDied)
{
Tracy.Message("Player died");
}
}
void DoSomething()
{
using (Tracy.Zone("DoSomething"))
{
// 你的代码
}
}
}
```
### 步骤 5: 启动 Tracy Profiler 并连接
1. **启动 Tracy Profiler**
```bash
# Windows
Tracy.exe
# macOS/Linux
./Tracy
```
2. **运行 Unity 游戏**
在 Unity Editor 中按 Play或运行构建的可执行文件。
3. **连接到 Tracy**
Tracy Profiler 会自动发现本地网络中的 Tracy 客户端,点击连接即可开始分析。
---
## 📊 使用 Tracy 分析性能
### 查看性能数据
Tracy Profiler 界面主要区域:
1. **时间线视图**
- 显示所有 Zone 的执行时间
- 颜色表示不同的调用栈深度
- 可以缩放和平移
2. **统计视图**
- 函数调用次数
- 总耗时、平均耗时、最小/最大耗时
- 排序和筛选功能
3. **帧视图**
- 查看每帧的性能
- 识别帧率波动
- 帧时间分布
4. **Plot 视图**
- 查看 `Tracy.Plot()` 绘制的数值曲线
- 实时监控变量变化
### 常用快捷键
- `鼠标滚轮`: 缩放时间线
- `鼠标中键拖拽`: 平移时间线
- `鼠标左键`: 选择 Zone 查看详情
- `Ctrl + F`: 搜索函数
- `Ctrl + Z`: 放大到选中的 Zone
---
## 🔧 常见问题排查
### 问题 1: DLL 加载失败
**错误信息**: `DllNotFoundException: UnityTracyPlugin`
**解决方案**:
1. 确认 DLL 文件在正确的目录
2. 检查 Plugin Import Settings 的平台配置
3. 确认 DLL 架构与 Unity 项目匹配x64/x86
4. Windows: 检查是否缺少 `vcruntime140.dll`(安装 Visual C++ Redistributable
### 问题 2: Tracy Profiler 无法连接
**症状**: Tracy Profiler 中看不到 Unity 应用
**解决方案**:
1. 确认防火墙允许 TCP 端口 8086
2. 检查 `TRACY_ON_DEMAND` 宏是否正确定义
3. 确认 `Tracy.Initialize()` 已被调用
4. 检查 Unity Console 是否有 Tracy 初始化消息
```csharp
// 在 Unity Console 应该看到:
// [Tracy] 性能分析器已初始化
```
### 问题 3: 性能数据不显示
**症状**: Tracy 已连接,但看不到任何 Zone
**解决方案**:
1. 确认代码中使用了 `Tracy.Zone()``ZoneScoped`
2. 确认 `Tracy.MarkFrame()` 在每帧被调用
3. 检查是否定义了 `TRACY_ENABLE` 编译符号
4. 在 Unity Editor 中,确认 Tracy Manager 的 "Enable On Start" 已勾选
### 问题 4: 编译错误
**常见编译错误**:
1. **找不到 Tracy.hpp**
```
fatal error: tracy/Tracy.hpp: No such file or directory
```
解决: 检查 `TRACY_ROOT` 路径是否正确
2. **链接错误 (Windows)**
```
error LNK2019: unresolved external symbol
```
解决: 确认链接了 `ws2_32.lib` 和 `dbghelp.lib`
3. **链接错误 (Linux)**
```
undefined reference to `pthread_create'
```
解决: 添加 `-lpthread -ldl` 链接选项
### 问题 5: Android/iOS 构建问题
**Android**:
1. 使用 Android NDK 编译
2. 确保为所有需要的 ABI 编译armeabi-v7a, arm64-v8a
3. 将 `.so` 文件放在 `Assets/Plugins/Android/libs/{ABI}/`
**iOS**:
1. 编译为静态库(.a
2. 在 Unity Build Settings 中设置 "Target SDK" 为 "Device SDK"
3. 确保代码签名正确
---
## 🎯 最佳实践
### 1. Zone 命名规范
```csharp
// ✅ 好的命名 - 清晰、描述性
using (Tracy.Zone("PlayerController.Move"))
using (Tracy.Zone("AI.UpdatePathfinding"))
using (Tracy.Zone("Render.DrawTerrain"))
// ❌ 不好的命名 - 模糊、无意义
using (Tracy.Zone("Function1"))
using (Tracy.Zone("Update"))
using (Tracy.Zone("Test"))
```
### 2. 适度使用 Zone
```csharp
void Update()
{
// ✅ 追踪主要的逻辑块
using (Tracy.Zone("Update"))
{
using (Tracy.Zone("ProcessInput"))
{
ProcessInput(); // 追踪大块逻辑
}
UpdateGameLogic(); // 内部有自己的 Zone
}
}
// ❌ 过度追踪会增加开销
void BadExample()
{
for (int i = 0; i < 10000; i++)
{
using (Tracy.Zone($"Iteration {i}")) // 太多 Zone
{
DoSomething();
}
}
}
```
### 3. 使用条件编译
```csharp
// 在生产构建中禁用细粒度追踪
#if TRACY_ENABLE
using (Tracy.Zone("DetailedAnalysis"))
{
// 详细的性能分析代码
}
#endif
```
### 4. 监控关键指标
```csharp
void LateUpdate()
{
// 监控帧率
Tracy.Plot("FPS", 1.0f / Time.deltaTime);
// 监控内存
Tracy.Plot("Memory (MB)", GC.GetTotalMemory(false) / 1024.0 / 1024.0);
// 监控对象计数
Tracy.Plot("Enemy Count", enemies.Count);
Tracy.Plot("Active Particles", particleSystem.particleCount);
// 监控物理
Tracy.Plot("Rigidbodies", FindObjectsOfType<Rigidbody>().Length);
}
```
### 5. 多线程命名
```csharp
using System.Threading;
void WorkerThread()
{
Tracy.SetThreadName("Worker Thread");
while (running)
{
using (Tracy.Zone("WorkerThread.Process"))
{
ProcessData();
}
}
}
```
---
## 📚 进阶主题
### 自定义构建配置
在 Unity 项目中创建 `link.xml` 防止代码剥离:
```xml
<linker>
<assembly fullname="Assembly-CSharp">
<namespace fullname="TracyProfiler" preserve="all"/>
</assembly>
</linker>
```
### 持久化性能数据
Tracy 支持保存性能数据到文件:
1. 在 Tracy Profiler 中,点击 "Save trace"
2. 选择保存位置(.tracy 文件)
3. 之后可以用 Tracy Profiler 打开查看
### 集成到 CI/CD
可以在自动化测试中使用 Tracy
```csharp
public class PerformanceTest
{
[Test]
public void TestPerformance()
{
Tracy.Initialize();
using (Tracy.Zone("PerformanceTest"))
{
// 运行性能测试
RunGameLoop(100); // 运行 100 帧
}
Tracy.Shutdown();
// 分析结果...
}
}
```
---
## 🔗 资源链接
- [Tracy 官方仓库](https://github.com/wolfpld/tracy)
- [Tracy 官方手册](https://github.com/wolfpld/tracy/releases/latest/download/tracy.pdf)
- [Unity Native Plugin 文档](https://docs.unity3d.com/Manual/NativePlugins.html)
- 本项目的完整文档: `UNITY_INTEGRATION_GUIDE.md`
---
## 💡 技巧和提示
1. **使用 Release 构建进行性能测试**
- Debug 构建会有大量额外开销
- 在 Unity 中创建专门的 "Profiling" 构建配置
2. **关闭 V-Sync 测试真实性能**
- V-Sync 会限制帧率
- 在 Project Settings > Quality 中关闭
3. **使用 Tracy 的统计功能**
- 查看函数调用次数
- 识别被频繁调用的函数
4. **比较不同实现**
- 使用 Tracy 比较算法性能
- A/B 测试优化效果
5. **定期保存 Trace 文件**
- 记录性能基准
- 跟踪性能变化趋势
---
## 🎉 完成!
现在你已经成功将 Tracy 集成到 Unity 项目中了!
开始使用 Tracy 分析你的游戏性能,找出瓶颈,优化代码吧!
如有问题,请参考完整文档 `UNITY_INTEGRATION_GUIDE.md` 或访问 Tracy 官方仓库。