--- description: Unity 调试信息与 Gizmo 可视化规范 globs: **/*.cs alwaysApply: false --- # Unity 调试与可视化规范 编写 MonoBehaviour 或与场景交互的脚本时,应添加合适的调试信息与可视化 Gizmo,便于编辑器内调试与问题定位。 ## 1. Gizmo 可视化 ### 何时添加 - **空间/范围相关**:中心点、半径、边界框、射线、碰撞区域 - **路径/轨道**:环形轨道、移动路径、连线 - **状态可视化**:当前朝向、选中高亮、有效/无效区域 ### 建议 - 用 `OnDrawGizmosSelected()`:仅在选中对象时绘制,减少干扰 - 用 `OnDrawGizmos()`:需始终可见的辅助线(如重要边界) - 使用 `#if UNITY_EDITOR` 包裹 Gizmo 代码,避免打进构建 - 颜色区分:绿色/青绿=有效/正常,黄/橙=参考点,红=警告/边界 ### 示例 ```csharp #if UNITY_EDITOR private void OnDrawGizmosSelected() { if (ringCenter == null) return; float r = ringRadius > 0f ? ringRadius : /* 从 transform 计算 */; if (r < 0.01f) return; Vector3 center = ringCenter.position; Gizmos.color = new Color(0.3f, 0.9f, 0.55f, 0.6f); // 绘制圆环轨迹 const int segments = 64; for (int i = 0; i < segments; i++) { float a0 = (float)i / segments * 2f * Mathf.PI; float a1 = (float)(i + 1) / segments * 2f * Mathf.PI; Vector3 p0 = center + new Vector3(Mathf.Cos(a0) * r, Mathf.Sin(a0) * r, center.z); Vector3 p1 = center + new Vector3(Mathf.Cos(a1) * r, Mathf.Sin(a1) * r, center.z); Gizmos.DrawLine(p0, p1); } Gizmos.color = new Color(1f, 0.5f, 0f, 0.8f); Gizmos.DrawWireSphere(center, 0.05f); } #endif ``` ## 2. 调试日志 ### 何时添加 - **配置缺失**:关键引用为 null 时用 `Debug.LogWarning` 提示 - **异常分支**:不应进入的逻辑用 `Debug.LogError` - **状态切换**:可选,重要状态变化用 `Debug.Log`(建议配合 `[Conditional("UNITY_EDITOR")]` 或 `#if UNITY_EDITOR` 限制编辑器内) ### 建议 - 使用 `this` 作为 context 参数,方便 Inspector 中定位对象 - 避免每帧/高频调用 `Debug.Log`,影响性能 ### 示例 ```csharp #if UNITY_EDITOR if (interactionCollider == null) { Debug.LogWarning($"[{GetType().Name}] 未找到 Collider2D!请添加或指定 interactionCollider。", this); } #endif ``` ## 3. 可选:Inspector 开关 对复杂 Gizmo 或大量日志,可在 Inspector 中加 Bool 开关: ```csharp [Header("调试")] [SerializeField] private bool showDebugGizmo = true; [SerializeField] private bool enableDebugLog = false; ```