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
| using System; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.ResourceManagement; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.ResourceManagement.ResourceProviders;
public class UnityLoadingFlowAnalyzer : MonoBehaviour { [Header("Unity底层加载流程分析配置")] public bool enableSystemCallTracing = true; public bool enablePerformanceCounters = true; public bool enableDependencyTracking = true; [System.Serializable] public class SystemCallTrace { public string callType; public string target; public float timestamp; public long memoryUsage; public string threadId; public Dictionary<string, object> parameters; } [System.Serializable] public class PerformanceCounter { public string name; public float value; public string unit; public DateTime updateTime; } [System.Serializable] public class LoadingFlowStep { public string stepName; public string componentName; public float startTime; public float endTime; public float duration; public List<SystemCallTrace> systemCalls; public List<PerformanceCounter> counters; public string status; public string details; } [System.Serializable] public class LoadingFlowProfile { public string bundleName; public List<LoadingFlowStep> steps; public Dictionary<string, object> contextData; public DateTime startTime; public DateTime endTime; public float totalTime; public List<string> dependencies; } private List<SystemCallTrace> callTraces = new List<SystemCallTrace>(); private Dictionary<string, PerformanceCounter> performanceCounters = new Dictionary<string, PerformanceCounter>(); private Dictionary<string, LoadingFlowProfile> flowProfiles = new Dictionary<string, LoadingFlowProfile>(); void Start() { Debug.Log("Unity底层加载流程分析器启动"); AnalyzeLoadingFlow(); } private void AnalyzeLoadingFlow() { Debug.Log("=== Unity底层加载流程分析 ==="); var flowAnalysis = new System.Text.StringBuilder(); flowAnalysis.AppendLine("Unity AssetBundle底层加载流程:"); flowAnalysis.AppendLine(); flowAnalysis.AppendLine("1. 资源管理器层 (Resource Manager Layer):"); flowAnalysis.AppendLine(" - Addressables系统入口"); flowAnalysis.AppendLine(" - 异步操作句柄管理"); flowAnalysis.AppendLine(" - 资源定位和依赖解析"); flowAnalysis.AppendLine(" - 缓存和生命周期管理"); flowAnalysis.AppendLine(); flowAnalysis.AppendLine("2. 资源提供者层 (Resource Provider Layer):"); flowAnalysis.AppendLine(" - IResourceProvider接口实现"); flowAnalysis.AppendLine(" - 具体资源类型的加载逻辑"); flowAnalysis.AppendLine(" - 资源创建和销毁"); flowAnalysis.AppendLine(" - 类型安全检查"); flowAnalysis.AppendLine(); flowAnalysis.AppendLine("3. Bundle系统层 (AssetBundle System Layer):"); flowAnalysis.AppendLine(" - AssetBundle.LoadFromFile/LoadFromMemory"); flowAnalysis.AppendLine(" - Bundle内部资源索引"); flowAnalysis.AppendLine(" - 依赖Bundle管理"); flowAnalysis.AppendLine(" - 内存映射和缓存"); flowAnalysis.AppendLine(); flowAnalysis.AppendLine("4. 文件系统层 (File System Layer):"); flowAnalysis.AppendLine(" - 物理文件读取"); flowAnalysis.AppendLine(" - 压缩数据解压"); flowAnalysis.AppendLine(" - 数据完整性校验"); flowAnalysis.AppendLine(" - 缓存机制"); flowAnalysis.AppendLine(); flowAnalysis.AppendLine("5. 底层系统层 (Low-level System Layer):"); flowAnalysis.AppendLine(" - 操作系统文件API"); flowAnalysis.AppendLine(" - 磁盘I/O操作"); flowAnalysis.AppendLine(" - 内存管理"); flowAnalysis.AppendLine(" - 线程同步"); Debug.Log(flowAnalysis.ToString()); AnalyzeLayerInteractions(); } private void AnalyzeLayerInteractions() { Debug.Log("=== 各层交互分析 ==="); var interactionAnalysis = new System.Text.StringBuilder(); interactionAnalysis.AppendLine("层间交互模式:"); interactionAnalysis.AppendLine(); interactionAnalysis.AppendLine("同步 vs 异步交互:"); interactionAnalysis.AppendLine("• 高层(Manager) -> 底层(System): 异步调用"); interactionAnalysis.AppendLine("• 底层(System) -> 高层(Manager): 回调通知"); interactionAnalysis.AppendLine("• 同层组件: 事件驱动或直接调用"); interactionAnalysis.AppendLine(); interactionAnalysis.AppendLine("数据流向:"); interactionAnalysis.AppendLine("• 请求: 上层 -> 下层 (加载指令)"); interactionAnalysis.AppendLine("• 响应: 下层 -> 上层 (加载结果)"); interactionAnalysis.AppendLine("• 错误: 任意层 -> 上层 (异常传播)"); interactionAnalysis.AppendLine(); interactionAnalysis.AppendLine("状态同步:"); interactionAnalysis.AppendLine("• 异步操作状态跟踪"); interactionAnalysis.AppendLine("• 资源引用计数管理"); interactionAnalysis.AppendLine("• 生命周期协调"); Debug.Log(interactionAnalysis.ToString()); } public LoadingFlowProfile SimulateLoadingFlow(string bundlePath, string assetName) { var profile = new LoadingFlowProfile { bundleName = System.IO.Path.GetFileNameWithoutExtension(bundlePath), steps = new List<LoadingFlowStep>(), contextData = new Dictionary<string, object>(), dependencies = new List<string>(), startTime = DateTime.Now }; profile.contextData["bundlePath"] = bundlePath; profile.contextData["assetName"] = assetName; profile.contextData["unityVersion"] = Application.unityVersion; profile.contextData["platform"] = Application.platform.ToString(); var step1 = ExecuteLoadingStep("资源管理器层", "ResourceManager", () => { SimulateResourceManagerOperations(); }); profile.steps.Add(step1); var step2 = ExecuteLoadingStep("资源提供者层", "ResourceProvider", () => { SimulateResourceProviderOperations(assetName); }); profile.steps.Add(step2); var step3 = ExecuteLoadingStep("Bundle系统层", "AssetBundleSystem", () => { SimulateBundleSystemOperations(bundlePath); }); profile.steps.Add(step3); var step4 = ExecuteLoadingStep("文件系统层", "FileSystem", () => { SimulateFileSystemOperations(bundlePath); }); profile.steps.Add(step4); var step5 = ExecuteLoadingStep("底层系统层", "LowLevelSystem", () => { SimulateLowLevelSystemOperations(); }); profile.steps.Add(step5); profile.endTime = DateTime.Now; profile.totalTime = (float)(profile.endTime - profile.startTime).TotalSeconds; flowProfiles[profile.bundleName] = profile; OutputLoadingFlowProfile(profile); return profile; } private LoadingFlowStep ExecuteLoadingStep(string stepName, string componentName, System.Action operation) { var step = new LoadingFlowStep { stepName = stepName, componentName = componentName, startTime = Time.realtimeSinceStartup, systemCalls = new List<SystemCallTrace>(), counters = new List<PerformanceCounter>(), status = "执行中" }; if (enableSystemCallTracing) { var startCall = new SystemCallTrace { callType = "StepStart", target = stepName, timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "component", componentName } } }; step.systemCalls.Add(startCall); } operation(); if (enablePerformanceCounters) { var counter = new PerformanceCounter { name = $"{stepName}_Duration", value = Time.realtimeSinceStartup - step.startTime, unit = "seconds", updateTime = DateTime.Now }; step.counters.Add(counter); } step.endTime = Time.realtimeSinceStartup; step.duration = step.endTime - step.startTime; step.status = "完成"; step.details = $"组件 {componentName} 完成 {stepName}"; if (enableSystemCallTracing) { var endCall = new SystemCallTrace { callType = "StepEnd", target = stepName, timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "duration", step.duration } } }; step.systemCalls.Add(endCall); } return step; } private void SimulateResourceManagerOperations() { System.Threading.Thread.Sleep(UnityEngine.Random.Range(10, 30)); if (enableSystemCallTracing) { var call = new SystemCallTrace { callType = "ResourceManagerOperation", target = "AddressablesSystem", timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "operation", "ResolveLocation" }, { "result", "Success" } } }; callTraces.Add(call); } } private void SimulateResourceProviderOperations(string assetName) { System.Threading.Thread.Sleep(UnityEngine.Random.Range(5, 20)); if (enableSystemCallTracing) { var call = new SystemCallTrace { callType = "ResourceProviderOperation", target = "AssetProvider", timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "assetName", assetName }, { "operation", "LoadAsset" } } }; callTraces.Add(call); } } private void SimulateBundleSystemOperations(string bundlePath) { System.Threading.Thread.Sleep(UnityEngine.Random.Range(20, 50)); if (enableSystemCallTracing) { var call = new SystemCallTrace { callType = "BundleSystemOperation", target = "AssetBundle", timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "bundlePath", bundlePath }, { "operation", "LoadAsset" } } }; callTraces.Add(call); } } private void SimulateFileSystemOperations(string bundlePath) { System.Threading.Thread.Sleep(UnityEngine.Random.Range(15, 40)); if (enableSystemCallTracing) { var call = new SystemCallTrace { callType = "FileSystemOperation", target = "FileIO", timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "filePath", bundlePath }, { "operation", "ReadFile" }, { "size", new System.IO.FileInfo(bundlePath).Length } } }; callTraces.Add(call); } } private void SimulateLowLevelSystemOperations() { System.Threading.Thread.Sleep(UnityEngine.Random.Range(5, 15)); if (enableSystemCallTracing) { var call = new SystemCallTrace { callType = "LowLevelOperation", target = "OS", timestamp = Time.realtimeSinceStartup, memoryUsage = GC.GetTotalMemory(false), threadId = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), parameters = new Dictionary<string, object> { { "operation", "MemoryAllocation" } } }; callTraces.Add(call); } } private void OutputLoadingFlowProfile(LoadingFlowProfile profile) { var output = new System.Text.StringBuilder(); output.AppendLine($"=== Unity底层加载流程分析: {profile.bundleName} ==="); output.AppendLine($"总耗时: {profile.totalTime:F3}s"); output.AppendLine($"平台: {profile.contextData["platform"]}"); output.AppendLine($"Unity版本: {profile.contextData["unityVersion"]}"); output.AppendLine(); output.AppendLine("流程步骤详情:"); foreach (var step in profile.steps) { output.AppendLine($" {step.stepName} ({step.componentName}):"); output.AppendLine($" 耗时: {step.duration:F3}s"); output.AppendLine($" 状态: {step.status}"); output.AppendLine($" 详情: {step.details}"); if (enableSystemCallTracing && step.systemCalls.Count > 0) { output.AppendLine(" 系统调用:"); foreach (var call in step.systemCalls) { output.AppendLine($" {call.callType}: {call.target}"); } } if (enablePerformanceCounters && step.counters.Count > 0) { output.AppendLine(" 性能计数:"); foreach (var counter in step.counters) { output.AppendLine($" {counter.name}: {counter.value} {counter.unit}"); } } output.AppendLine(); } Debug.Log(output.ToString()); } public string AnalyzePerformanceBottlenecks(string bundleName) { if (!flowProfiles.ContainsKey(bundleName)) { return $"未找到Bundle {bundleName} 的流程分析数据"; } var profile = flowProfiles[bundleName]; var analysis = new System.Text.StringBuilder(); analysis.AppendLine($"=== {bundleName} 性能瓶颈分析 ==="); var slowestStep = profile.steps[0]; foreach (var step in profile.steps) { if (step.duration > slowestStep.duration) { slowestStep = step; } } analysis.AppendLine($"最耗时步骤: {slowestStep.stepName} ({slowestStep.componentName}) - {slowestStep.duration:F3}s"); if (enableSystemCallTracing) { var callStats = new Dictionary<string, int>(); foreach (var step in profile.steps) { foreach (var call in step.systemCalls) { if (!callStats.ContainsKey(call.callType)) { callStats[call.callType] = 0; } callStats[call.callType]++; } } analysis.AppendLine("系统调用统计:"); foreach (var kvp in callStats) { analysis.AppendLine($" {kvp.Key}: {kvp.Value} 次"); } } analysis.AppendLine(); analysis.AppendLine("优化建议:"); if (slowestStep.componentName.Contains("FileSystem")) { analysis.AppendLine("• 优化文件I/O性能"); analysis.AppendLine("• 考虑使用SSD存储"); analysis.AppendLine("• 优化Bundle大小和压缩"); } else if (slowestStep.componentName.Contains("BundleSystem")) { analysis.AppendLine("• 优化Bundle内部结构"); analysis.AppendLine("• 考虑资源分包策略"); analysis.AppendLine("• 检查压缩算法选择"); } else if (slowestStep.componentName.Contains("ResourceManager")) { analysis.AppendLine("• 优化资源管理策略"); analysis.AppendLine("• 考虑预加载和缓存"); analysis.AppendLine("• 检查依赖关系"); } return analysis.ToString(); } public string GetSystemPerformanceOverview() { var overview = new System.Text.StringBuilder(); overview.AppendLine("=== Unity底层加载系统性能概览 ==="); overview.AppendLine($"分析的Bundle数量: {flowProfiles.Count}"); overview.AppendLine($"记录的系统调用数: {callTraces.Count}"); overview.AppendLine($"性能计数器数量: {performanceCounters.Count}"); overview.AppendLine($"启用系统调用追踪: {enableSystemCallTracing}"); overview.AppendLine($"启用性能计数器: {enablePerformanceCounters}"); overview.AppendLine($"启用依赖追踪: {enableDependencyTracking}"); if (flowProfiles.Count > 0) { float totalDuration = 0; foreach (var profile in flowProfiles.Values) { totalDuration += profile.totalTime; } float avgDuration = totalDuration / flowProfiles.Count; overview.AppendLine(); overview.AppendLine($"平均加载耗时: {avgDuration:F3}s"); var sortedProfiles = new List<LoadingFlowProfile>(flowProfiles.Values); sortedProfiles.Sort((a, b) => b.totalTime.CompareTo(a.totalTime)); overview.AppendLine("最慢的3个Bundle:"); for (int i = 0; i < Math.Min(3, sortedProfiles.Count); i++) { overview.AppendLine($" {sortedProfiles[i].bundleName}: {sortedProfiles[i].totalTime:F3}s"); } } return overview.ToString(); } void OnDestroy() { Debug.Log("Unity底层加载流程分析器清理完成"); } }
|