Unity中如何正确排除自身,对比子对象Transform做矩形重叠检测
解决Unity中Rect重叠检测时无法排除当前对象的问题
我来帮你搞定这个问题!你遇到的核心问题是引用对比的类型不匹配,导致没法正确跳过当前正在操作的对象。
问题根源
你现在写的判断条件!GameObject.ReferenceEquals(child_t, ghost_rt)里,child_t是Transform类型,而ghost_rt是RectTransform类型——哪怕它们属于同一个GameObject,这两个组件的引用也是完全不同的,所以这个对比永远会返回true(也就是说,你永远不会跳过当前对象)。
正确的解决方案
你只需要把对比的对象改成同类型的引用就行,有两种简单的实现方式:
方案1:对比Transform引用
先获取当前操作对象的Transform,然后和循环里的子Transform直接对比:
RectTransform ghost_rt = Ghost.GetComponent<RectTransform>(); Transform ghostTransform = Ghost.transform; // 拿到当前对象的Transform组件 Rect ghost_r = new Rect(ghost_rt.anchoredPosition, new Vector2(ghost_rt.rect.width, ghost_rt.rect.height)); bool overlaps = false; foreach (Transform child_t in Dst.transform) { // 对比两个Transform的引用,跳过当前对象 if (!GameObject.ReferenceEquals(child_t, ghostTransform)) { RectTransform rt = child_t.GetComponent<RectTransform>(); Rect cmp_r = new Rect(rt.anchoredPosition, new Vector2(rt.rect.width, rt.rect.height)); // DebugText.text += "cmp_r:" + cmp_r + "\n"; if (cmp_r.Overlaps(ghost_r)) { overlaps = true; break; } } }
方案2:对比GameObject引用
直接对比两个对象的GameObject实例,这种方式更直观,也不容易出错:
RectTransform ghost_rt = Ghost.GetComponent<RectTransform>(); Rect ghost_r = new Rect(ghost_rt.anchoredPosition, new Vector2(ghost_rt.rect.width, ghost_rt.rect.height)); bool overlaps = false; foreach (Transform child_t in Dst.transform) { // 对比GameObject实例,跳过当前对象 if (!GameObject.ReferenceEquals(child_t.gameObject, Ghost)) { RectTransform rt = child_t.GetComponent<RectTransform>(); Rect cmp_r = new Rect(rt.anchoredPosition, new Vector2(rt.rect.width, rt.rect.height)); // DebugText.text += "cmp_r:" + cmp_r + "\n"; if (cmp_r.Overlaps(ghost_r)) { overlaps = true; break; } } }
额外提示
如果你需要频繁做这种检测,建议提前把当前对象的引用存下来,避免重复获取组件;另外,Rect.Overlaps方法默认是包含边界接触的,如果需要排除边界接触,可以传入第二个参数true(比如cmp_r.Overlaps(ghost_r, true))。
内容的提问来源于stack exchange,提问作者Olivier Pons
相关产品推荐
相关产品推荐

