From 0a98898c265e6f0da4234adc4afc468e6a024983 Mon Sep 17 00:00:00 2001 From: yangbear Date: Sun, 12 Jul 2026 03:48:49 +0800 Subject: [PATCH] Fix NullReferenceException caused by aggressive collider destruction in Editor --- .../Scripts/Interaction/PingClickHandler.cs | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/Assets/Scripts/Interaction/PingClickHandler.cs b/Assets/Scripts/Interaction/PingClickHandler.cs index f7f0e3c..3a484f8 100644 --- a/Assets/Scripts/Interaction/PingClickHandler.cs +++ b/Assets/Scripts/Interaction/PingClickHandler.cs @@ -16,29 +16,27 @@ public class PingClickHandler : MonoBehaviour if (_modelRenderer == null) _modelRenderer = GetComponentInChildren(); foreach (var r in GetComponentsInChildren(true)) r.enabled = false; - // 彻底清掉旧的 Collider,重新添加一个绝对靠谱的 SphereCollider - var colliders = GetComponents(); - foreach(var c in colliders) + // 修复之前粗暴销毁导致的编辑器报错,改为安全地复用或添加 Collider + var col = GetComponent(); + if (col == null) { - Destroy(c); + col = gameObject.AddComponent(); } - // 重新添加足够大、形状简单的球形碰撞器 - var sphere = gameObject.AddComponent(); - // 获取物体本身的渲染边界,如果没有则使用固定值 - if (_modelRenderer != null) + if (col is SphereCollider sphere) { - // 通过 bounds 的大小来估算一个适合的半径 - float maxDim = Mathf.Max(_modelRenderer.bounds.size.x, Mathf.Max(_modelRenderer.bounds.size.y, _modelRenderer.bounds.size.z)); + float maxDim = 0.5f; + if (_modelRenderer != null) + maxDim = Mathf.Max(_modelRenderer.bounds.size.x, Mathf.Max(_modelRenderer.bounds.size.y, _modelRenderer.bounds.size.z)); sphere.radius = Mathf.Max(maxDim * 0.6f, 0.5f); } - else + else if (col is BoxCollider box) { - sphere.radius = 0.5f; + box.size = new Vector3(Mathf.Max(box.size.x, 0.8f), Mathf.Max(box.size.y, 0.8f), Mathf.Max(box.size.z, 0.8f)); } // 强制碰撞体处于启用状态 - sphere.enabled = true; + col.enabled = true; CreateOutlineMesh(); _modelShown = false; @@ -228,7 +226,6 @@ public class PingClickHandler : MonoBehaviour { _modelShown = false; - // 【关键修复点:重置状态时确保重新添加或修复 Collider】 var col = GetComponent(); if (col == null) {