Unity中Gizmos触碰障碍层物体时变色失败及空引用报错问题
问题解决:Unity Grid Gizmos空引用与不显示问题
核心问题分析
- 空引用错误根源:原
OnDrawGizmos代码在grid == null的分支里尝试访问grid[x,y],直接触发空引用,属于逻辑判断与执行代码的矛盾错误。 - Gizmos不显示原因:
grid仅在运行时的Start()方法中初始化,但OnDrawGizmos在编辑模式下就会执行,此时grid仍为null,修改后的代码判断grid != null才绘制,自然不会显示任何Gizmos。
解决方案步骤
1. 让Grid在编辑模式下也能初始化
通过[ContextMenu]标签给GenerateGrid()添加右键菜单,方便手动在编辑模式下生成Grid;同时在OnDrawGizmos里做兜底判断,确保Grid未初始化时自动生成(可根据性能需求选择是否保留自动生成逻辑)。
2. 修复Gizmos绘制逻辑
确保只有当grid存在时才去访问其中的Node,同时让编辑模式下也能预览Gizmos效果。
3. 完善物理检测细节
调整Physics.CheckBox的检测尺寸,确保和单元格大小匹配,避免检测范围偏差。
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class Grid : MonoBehaviour { Node[,] grid; [SerializeField] int width = 25; [SerializeField] int length = 25; [SerializeField] float cellSize = 1f; [SerializeField] LayerMask obstacleLayer; private void Start() { GenerateGrid(); } // 添加右键菜单,编辑模式下可手动生成Grid [ContextMenu("Generate Grid")] private void GenerateGrid() { grid = new Node[length, width]; CheckPassableTerrain(); } private void CheckPassableTerrain() { for (int y = 0; y < width; y++) { for (int x = 0; x < length; x++) { Vector3 worldPosition = GetWorldPosition(x, y); // 调整CheckBox半尺寸,确保与单元格大小匹配 Vector3 halfSize = Vector3.one * cellSize * 0.5f; bool passable = !Physics.CheckBox(worldPosition, halfSize, Quaternion.identity, obstacleLayer); grid[x, y] = new Node(); grid[x, y].passable = passable; } } } private void OnDrawGizmos() { // 兜底:若Grid未初始化则自动生成(编辑模式下也生效) if (grid == null) { GenerateGrid(); } // Grid存在时绘制Gizmos for (int y = 0; y < width; y++) { for (int x = 0; x < length; x++) { Vector3 pos = GetWorldPosition(x, y); Gizmos.color = grid[x, y].passable ? Color.white : Color.red; // 绘制的Cube尺寸与单元格大小一致 Gizmos.DrawCube(pos, Vector3.one * cellSize); } } } private Vector3 GetWorldPosition(int x, int y) { return new Vector3(transform.position.x + (x * cellSize), 0.5f, transform.position.z + (y * cellSize)); } } // 补充Node类定义(确保脚本可正常运行) public class Node { public bool passable; }
额外说明
- 编辑模式下,可直接在Inspector面板右键该脚本组件,选择
Generate Grid手动生成Grid,Gizmos会立即显示。 - 若担心自动生成频繁刷新影响性能,可去掉
OnDrawGizmos里的自动生成逻辑,仅用右键菜单手动触发。 - 需确认
obstacleLayer已在Inspector中正确选择Obstacle层,否则物理检测会失效。
内容的提问来源于stack exchange,提问作者NectarNoks
相关产品推荐
相关产品推荐

