10-08-实战-调试与性能分析

实战-调试与性能分析

篇章:10-实战篇-从零搭建
状态:已完成
阅读时间:约 25 分钟


一、引言

1.1 本章在系列中的定位

YooAsset 作为运行时资源管理框架,性能问题和调试困难是开发者最常遇到的两类问题。本章系统讲解:

  • YooAsset 调试工具
  • 常见性能瓶颈及优化
  • 内存分析与治理
  • 加载慢的根因分析

1.2 本章要解决的核心问题

  • 如何快速定位 YooAsset 的问题?
  • 加载慢、卡顿的原因有哪些?
  • 内存泄漏如何排查?
  • 性能调优的标准流程是什么?

1.3 阅读前置要求

  • 完成 10-01 到 10-07
  • 了解 Unity Profiler
  • 了解 C# 性能分析基础

二、YooAsset 调试工具

2.1 Editor 调试窗口

YooAsset 提供了 YooAssetDebugger 窗口:

YooAsset → Debug Window

窗口中可以看到:

标签 内容
资源列表 已加载的所有资源
Package 状态 各 Package 的加载/卸载状态
异步操作 当前正在执行的异步操作
引用计数 每个资源的引用次数
缓存大小 缓存占用的磁盘空间

2.2 Debug 模式

public class DebugModeSetup
{
    [RuntimeInitializeOnLoadMethod]
    public static void Setup()
    {
        // 启用调试模式
        YooAssetSettings.VerboseLog = true;
        
        // 启用诊断事件
        YooAssetDiagnostics.OnOperationStart += op => 
            Debug.Log($"[YooAsset] Start: {op.GetType().Name}");
        YooAssetDiagnostics.OnOperationComplete += op => 
            Debug.Log($"[YooAsset] Complete: {op.GetType().Name}, Status: {op.Status}");
        YooAssetDiagnostics.OnOperationError += (op, err) => 
            Debug.LogError($"[YooAsset] Error: {err}");
    }
}

2.3 日志系统

public class CustomLogger
{
    public static void Setup()
    {
        YooAssetLogger.LogHandler = (level, message) =>
        {
            switch (level)
            {
                case ELogLevel.Debug:
                    Debug.Log($"[YooAsset-D] {message}");
                    break;
                case ELogLevel.Info:
                    Debug.Log($"[YooAsset-I] {message}");
                    break;
                case ELogLevel.Warning:
                    Debug.LogWarning($"[YooAsset-W] {message}");
                    break;
                case ELogLevel.Error:
                    Debug.LogError($"[YooAsset-E] {message}");
                    break;
            }
        };
    }
}

2.4 关键路径日志

public class KeyPathLogger
{
    public static void LogKeyPaths()
    {
        // 启动时
        Debug.Log($"[YooAsset] YooAsset Path: {YooAssets.GetYooAssetRoot()}");
        Debug.Log($"[YooAsset] Cache Path: {YooAssets.GetCacheRoot()}");
        Debug.Log($"[YooAsset] Current Package: {YooAssets.GetCurrentPackageName()}");
        Debug.Log($"[YooAsset] Manifest Version: {YooAssets.GetPackageVersion()}");
    }
}

三、性能分析工具

3.1 Unity Profiler

3.1.1 CPU 性能

Window → Analysis → Profiler

在 YooAsset 相关代码处打自定义 Profiler 标签:

public class ProfiledLoader
{
    public async Task<T> LoadProfiled<T>(string location) where T : Object
    {
        using (var scope = CustomSampler.Create($"YooAsset.Load.{typeof(T).Name}").Begin())
        {
            var op = YooAssets.LoadAssetAsync<T>(location);
            await op.Task;
            return op.Status == EOperationStatus.Succeed ? op.Result : null;
        }
    }
}

3.1.2 内存分析

public class MemoryProfilerHelper
{
    public void CaptureSnapshot(string name)
    {
        UnityEngine.Profiling.Profiler.BeginSample($"YooAsset.{name}");
        // 触发 YooAsset 内部统计
        YooAssetDiagnostics.DumpState();
        UnityEngine.Profiling.Profiler.EndSample();
    }
}

3.1.3 网络分析

public class NetworkProfiler
{
    private readonly Dictionary<string, long> _downloadSizes = new();
    private readonly Dictionary<string, long> _downloadTimes = new();
    
    public void RecordDownload(string url, long size, long ms)
    {
        _downloadSizes[url] = size;
        _downloadTimes[url] = ms;
        
        var speed = size / (ms / 1000.0f) / 1024;  // KB/s
        Debug.Log($"[Network] {url}: {size / 1024}KB in {ms}ms ({speed:F1}KB/s)");
    }
}

3.2 YooAsset 性能报告

public class PerformanceReport
{
    public class ResourceLoadInfo
    {
        public string Location;
        public long LoadTimeMs;
        public long MemoryBytes;
        public int RefCount;
    }
    
    private readonly List<ResourceLoadInfo> _infos = new();
    
    public void Record(string location, long loadTimeMs, long memoryBytes)
    {
        _infos.Add(new ResourceLoadInfo
        {
            Location = location,
            LoadTimeMs = loadTimeMs,
            MemoryBytes = memoryBytes
        });
    }
    
    public string GenerateReport()
    {
        var sb = new StringBuilder();
        sb.AppendLine("=== YooAsset Performance Report ===");
        sb.AppendLine($"Total Resources: {_infos.Count}");
        sb.AppendLine($"Total Time: {_infos.Sum(i => i.LoadTimeMs)}ms");
        sb.AppendLine($"Total Memory: {_infos.Sum(i => i.MemoryBytes) / 1024 / 1024}MB");
        
        // 加载最慢的 10 个
        sb.AppendLine("\n--- Top 10 Slowest ---");
        foreach (var info in _infos.OrderByDescending(i => i.LoadTimeMs).Take(10))
        {
            sb.AppendLine($"{info.LoadTimeMs}ms: {info.Location}");
        }
        
        // 内存最大的 10 个
        sb.AppendLine("\n--- Top 10 Largest ---");
        foreach (var info in _infos.OrderByDescending(i => i.MemoryBytes).Take(10))
        {
            sb.AppendLine($"{info.MemoryBytes / 1024}KB: {info.Location}");
        }
        
        return sb.ToString();
    }
}

四、加载慢的根因分析

4.1 加载慢的常见原因

原因 表现 占比
Bundle 太大 单个加载慢 30%
依赖链过深 等待依赖时间长 25%
重复加载 缓存未命中 20%
主线程阻塞 加载过程中卡顿 15%
磁盘 IO 慢 读取慢 10%

4.2 Bundle 过大优化

4.2.1 检测大 Bundle

public class LargeBundleDetector
{
    public void Detect()
    {
        var buildMap = AssetBundleCollector.BuildMap();
        
        foreach (var bundle in buildMap.BundleList)
        {
            if (bundle.FileSize > 10 * 1024 * 1024)  // 10MB
            {
                Debug.LogWarning($"[LargeBundle] {bundle.BundleName}: {bundle.FileSize / 1024 / 1024}MB");
            }
        }
    }
}

4.2.2 优化方案

  1. 拆分 Bundle:将大 Bundle 拆为多个小 Bundle
  2. 启用压缩:使用 LZ4 压缩
  3. 剔除冗余:移除未使用的资源
// 拆分示例:将一个 50MB 的 Bundle 拆为 5 个 10MB
public class BundleSplitter : IPackRule
{
    public bool Match(AssetInfo info) => true;
    
    public string GetBundleName(AssetInfo info)
    {
        // 按文件大小动态分配
        var hash = info.FilePath.GetHashCode();
        var shard = Math.Abs(hash) % 5;
        return $"shard_{shard}";
    }
}

4.3 依赖链过深优化

4.3.1 检测依赖深度

public class DependencyDepthAnalyzer
{
    public int CalculateDepth(BundleInfo bundle, BuildMap buildMap)
    {
        if (bundle.Dependencies == null || bundle.Dependencies.Count == 0)
            return 0;
        
        int maxDepth = 0;
        foreach (var dep in bundle.Dependencies)
        {
            var depBundle = buildMap.GetBundle(dep);
            if (depBundle != null)
            {
                var depth = CalculateDepth(depBundle, buildMap) + 1;
                maxDepth = Math.Max(maxDepth, depth);
            }
        }
        return maxDepth;
    }
}

4.3.2 优化方案

  1. 合并浅层依赖:将依赖深度 ≤ 2 的资源合并
  2. 异步加载:分层加载
  3. 预加载:在玩家看到资源前加载
public class LayeredLoader
{
    public async Task LoadLayered(string rootLocation)
    {
        // 1. 先加载最关键的资源
        var criticalOps = new[]
        {
            YooAssets.LoadAssetAsync<Sprite>($"{rootLocation}/hero"),
            YooAssets.LoadAssetAsync<Sprite>($"{rootLocation}/ui_main")
        };
        await Task.WhenAll(criticalOps.Select(op => op.Task));
        
        // 2. 关键资源已就绪,玩家可以继续
        
        // 3. 后台加载次要资源
        var nonCriticalOps = new[]
        {
            YooAssets.LoadAssetAsync<AudioClip>($"{rootLocation}/bgm"),
            YooAssets.LoadAssetAsync<Material>($"{rootLocation}/effects")
        };
        await Task.WhenAll(nonCriticalOps.Select(op => op.Task));
    }
}

4.4 重复加载优化

4.4.1 检测重复加载

public class DuplicateLoadDetector
{
    private readonly Dictionary<string, int> _loadCounts = new();
    
    public void TrackLoad(string location)
    {
        if (!_loadCounts.ContainsKey(location))
            _loadCounts[location] = 0;
        _loadCounts[location]++;
    }
    
    public void Report()
    {
        foreach (var kvp in _loadCounts.Where(kv => kv.Value > 1))
        {
            Debug.LogWarning($"[DuplicateLoad] {kvp.Key} 被加载 {kvp.Value} 次");
        }
    }
}

4.4.2 优化方案

  1. 资源缓存:在业务层缓存常用资源
  2. 引用计数:复用已加载的 op
  3. 预加载:在合适时机提前加载
public class ResourceCache
{
    private readonly Dictionary<string, AsyncOperationBase> _cache = new();
    
    public async Task<T> Get<T>(string location) where T : Object
    {
        // 检查缓存
        if (_cache.TryGetValue(location, out var cachedOp))
        {
            if (cachedOp.IsDone)
                return (cachedOp as AssetOperation).Result as T;
        }
        
        // 加载新资源
        var op = YooAssets.LoadAssetAsync<T>(location);
        _cache[location] = op;
        await op.Task;
        
        return op.Status == EOperationStatus.Succeed ? op.Result : null;
    }
}

4.5 主线程阻塞优化

4.5.1 检测主线程耗时

public class MainThreadBlockDetector
{
    public async Task<T> DetectBlocking<T>(Func<Task<T>> loadFunc) where T : Object
    {
        var sw = Stopwatch.StartNew();
        var result = await loadFunc();
        sw.Stop();
        
        if (sw.ElapsedMilliseconds > 16)  // 超过一帧
        {
            Debug.LogWarning($"[MainBlock] 加载耗时 {sw.ElapsedMilliseconds}ms");
        }
        
        return result;
    }
}

4.5.2 优化方案

  1. 避免同步加载:所有加载都用 Async
  2. 分帧加载:每帧加载 N 个
  3. 预加载:在 Loading 阶段完成
public class FrameSpreadLoader
{
    public async Task<List<T>> LoadInFrames<T>(List<string> locations, int perFrame = 5) where T : Object
    {
        var results = new List<T>();
        for (int i = 0; i < locations.Count; i += perFrame)
        {
            var batch = locations.Skip(i).Take(perFrame);
            var batchResults = await Task.WhenAll(batch.Select(loc => LoadAsync<T>(loc)));
            results.AddRange(batchResults);
            
            // 等一帧
            await Task.Yield();
        }
        return results;
    }
}

五、内存分析与治理

5.1 内存分析工具

5.1.1 MemoryProfiler(Unity 官方)

Window → Analysis → MemoryProfiler

可以查看:

  • 资源占用排行
  • 引用关系图
  • 重复资源

5.1.2 Profiler 内存视图

Window → Analysis → Profiler → Memory

5.1.3 自定义内存分析

public class MemoryAnalyzer
{
    public void Analyze()
    {
        long totalMemory = Profiler.GetTotalAllocatedMemoryLong();
        long textureMemory = Profiler.GetAllocatedMemoryForGraphicsDriver();
        long meshMemory = Profiler.GetAllocatedMemoryForGraphicsDriver();
        
        Debug.Log($"[Memory] Total: {totalMemory / 1024 / 1024}MB");
        Debug.Log($"[Memory] GPU: {textureMemory / 1024 / 1024}MB");
        
        // YooAsset 内部统计
        var stats = YooAssets.GetMemoryStats();
        Debug.Log($"[YooAsset] Bundle Count: {stats.BundleCount}");
        Debug.Log($"[YooAsset] Resource Count: {stats.ResourceCount}");
    }
}

5.2 内存泄漏排查

5.2.1 引用计数泄漏

public class RefCountLeakDetector
{
    public void Check()
    {
        var infos = YooAssets.GetRefCountInfos();
        
        foreach (var info in infos)
        {
            if (info.RefCount > 0 && info.LastUsedTime < DateTime.Now.AddHours(-1))
            {
                Debug.LogWarning($"[Leak] {info.Location} 引用计数 {info.RefCount}, 1 小时未使用");
            }
        }
    }
}

5.2.2 Bundle 泄漏

public class BundleLeakDetector
{
    public void Check()
    {
        var bundles = YooAssets.GetLoadedBundles();
        
        foreach (var bundle in bundles)
        {
            if (bundle.RefCount == 0 && bundle.LoadedTime < DateTime.Now.AddMinutes(-30))
            {
                Debug.LogWarning($"[BundleLeak] {bundle.Name} 30 分钟未使用");
                // 主动卸载
                // YooAssets.UnloadBundle(bundle.Name);
            }
        }
    }
}

5.2.3 资源泄漏修复

public class LeakFixer
{
    public void FixLeaks()
    {
        // 1. 强制释放未使用资源
        Resources.UnloadUnusedAssets();
        
        // 2. 释放 YooAsset 缓存
        YooAssets.ClearUnusedCache();
        
        // 3. 强制 GC
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        
        // 4. 验证
        var afterMemory = Profiler.GetTotalAllocatedMemoryLong();
        Debug.Log($"[AfterFix] Memory: {afterMemory / 1024 / 1024}MB");
    }
}

5.3 内存优化技巧

5.3.1 资源按需加载

// 不要一次性加载所有资源
// 错误:
public async Task LoadAllUI()
{
    var allUI = new[] { "ui_login", "ui_main", "ui_battle", "ui_shop" };
    foreach (var ui in allUI)
        await LoadUIAsync(ui);
}

// 正确:分场景加载
public async Task LoadUIForCurrentScene(string scene)
{
    var uiList = GetUIForScene(scene);
    foreach (var ui in uiList)
        await LoadUIAsync(ui);
}

5.3.2 资源池

public class GameObjectPool
{
    private readonly Dictionary<string, Queue<GameObject>> _pool = new();
    private readonly Dictionary<string, GameObject> _prefabs = new();
    
    public async Task<GameObject> Get(string prefabAddress, Transform parent = null)
    {
        if (!_pool.ContainsKey(prefabAddress))
            _pool[prefabAddress] = new Queue<GameObject>();
        
        if (_pool[prefabAddress].Count > 0)
        {
            var go = _pool[prefabAddress].Dequeue();
            go.SetActive(true);
            return go;
        }
        
        // 池中没有,加载
        if (!_prefabs.ContainsKey(prefabAddress))
        {
            var op = YooAssets.LoadAssetAsync<GameObject>(prefabAddress);
            await op.Task;
            _prefabs[prefabAddress] = op.Result;
        }
        
        return Object.Instantiate(_prefabs[prefabAddress], parent);
    }
    
    public void Return(string prefabAddress, GameObject go)
    {
        go.SetActive(false);
        _pool[prefabAddress].Enqueue(go);
    }
}

5.3.3 Texture 优化

public class TextureOptimizer
{
    public void Optimize(Texture2D texture)
    {
        // 1. 降低分辨率
        if (texture.width > 1024)
        {
            // 缩放
        }
        
        // 2. 使用 ETC2/ASTC 压缩
        // 在 Editor 中配置
    }
}

六、Profile 实战

6.1 CPU 性能分析

public class CPUProfiler
{
    public async Task ProfileLoad()
    {
        // 1. CPU 占用基线
        var baseline = Profiler.GetTotalAllocatedMemoryLong();
        
        // 2. 加载资源
        var sw = Stopwatch.StartNew();
        var op = YooAssets.LoadAssetAsync<GameObject>("test_hero");
        await op.Task;
        sw.Stop();
        
        // 3. 输出
        Debug.Log($"[CPU] Load time: {sw.ElapsedMilliseconds}ms");
        Debug.Log($"[CPU] Memory delta: {(Profiler.GetTotalAllocatedMemoryLong() - baseline) / 1024}KB");
    }
}

6.2 内存快照

public class MemorySnapshot
{
    public void TakeSnapshot(string name)
    {
        // 1. 触发 YooAsset 内部统计
        YooAssets.DumpState(name);
        
        // 2. 触发 Unity 内存快照
        // MemoryProfiler.TakeSnapshot($"{name}.snap", path => { });
    }
}

6.3 GPU 性能

public class GPUProfiler
{
    public void AnalyzeGPU()
    {
        // 1. DrawCall
        Debug.Log($"[GPU] DrawCall: {UnityStats.drawCalls}");
        Debug.Log($"[GPU] SetPass: {UnityStats.setPassCalls}");
        
        // 2. 三角形
        Debug.Log($"[GPU] Triangles: {UnityStats.triangles}");
        Debug.Log($"[GPU] Vertices: {UnityStats.vertices}");
    }
}

七、构建性能优化

7.1 构建时间优化

public class BuildTimeOptimizer
{
    public void Optimize()
    {
        // 1. 启用增量构建
        var buildParams = new BuildParameters
        {
            IncrementalBuild = true,
        };
        
        // 2. 关闭类型树
        buildParams.WriteTypeTree = false;
        
        // 3. 减少 Bundle 数量
        // 调整 PackRule
    }
}

7.2 构建产物优化

public class BuildOutputOptimizer
{
    public void Optimize()
    {
        // 1. 启用 LZ4 压缩
        var buildParams = new BuildParameters
        {
            CompressOption = ECompressOption.LZ4,
        };
        
        // 2. 启用共享包
        buildParams.EnableSharedPackRule = true;
        
        // 3. 设置最大 Bundle 大小
        buildParams.MaxBundleSize = 10 * 1024 * 1024;  // 10MB
    }
}

八、调试技巧

8.1 启用详细日志

public class VerboseLog
{
    [RuntimeInitializeOnLoadMethod]
    public static void Enable()
    {
        YooAssetSettings.VerboseLog = true;
        YooAssetSettings.LogLevel = ELogLevel.Debug;
    }
}

8.2 模拟网络慢

public class NetworkSimulator
{
    public static int SimulatedLatencyMs = 0;
    public static int SimulatedPacketLossPercent = 0;
    
    public static async Task<T> SimulateAsync<T>(Task<T> task)
    {
        await Task.Delay(SimulatedLatencyMs);
        return await task;
    }
}

8.3 模拟资源失败

public class ResourceFailureSimulator
{
    public static List<string> Blacklist = new();
    
    public static bool ShouldFail(string location)
    {
        return Blacklist.Contains(location);
    }
}

九、性能调优流程

9.1 标准调优流程

[1. 基线测量]
    ├── 记录当前性能数据
    │   ├── 启动时间
    │   ├── 加载时间
    │   ├── 内存占用
    │   └── 帧率
    │
    ▼
[2. 瓶颈定位]
    ├── Profiler 分析
    │   ├── CPU Profile
    │   ├── Memory Profile
    │   └── Network Profile
    │
    ▼
[3. 优化实施]
    ├── 针对性优化
    │   ├── Bundle 拆分
    │   ├── 依赖优化
    │   ├── 缓存优化
    │   └── 加载策略优化
    │
    ▼
[4. 效果验证]
    ├── 重新测量
    │   ├── 对比优化前后
    │   └── 确认无回退
    │
    ▼
[5. 上线灰度]
    ├── 5% → 20% → 100%
    └── 监控线上数据

9.2 调优案例

案例:启动加载慢

基线:3.2 秒
瓶颈:Hero 角色 Prefab 依赖 20 个 Bundle,依赖链深度 5
优化:
  1. 拆分依赖:核心依赖 5 个,非核心 15 个
  2. 异步加载:核心同步,非核心后台
  3. 预加载:在 Loading 阶段预先加载
结果:1.5 秒(提升 53%)

十、总结

10.1 本章要点回顾

  • 调试工具:Debug Window、Verbose Log、Custom Profiler
  • 性能分析:Profiler、Memory、Network 分析
  • 加载慢优化:Bundle 大小、依赖深度、重复加载、主线程阻塞
  • 内存治理:泄漏检测、资源池、按需加载
  • 调优流程:基线 → 定位 → 优化 → 验证 → 灰度

10.2 与前后章节的关联

  • 前章:10-07 介绍了热更新流程实现
  • 本章:聚焦调试与性能分析
  • 后章:10-09 将介绍常见问题与解决方案

10.3 实践建议

  1. 性能监控常态化:每个加载都要有 Profile
  2. 内存泄漏必查:每次发版前跑一遍泄漏检测
  3. 优化要有数据:凭感觉优化是最危险的
  4. 避免过度优化:90% 的项目用不到极致优化
  5. Profile First:先 Profile,再优化

上一篇:热更新流程实现
下一篇:常见问题与解决方案

posted @ 2026-11-19 11:55  SmalBox  阅读(8)  评论(0)    收藏  举报