当前位置:   article > 正文

关于unity射线检测空引用的问题_unity 射线检测为啥为空

unity 射线检测为啥为空
           startPos = transform.position + transform.right * 0.6f;
            // 每条射线都在forward_left的基础上偏转一点,最后一个正好偏转90度到视线最右侧
            Vector3 v = Quaternion.Euler(0, 0, (90.0f / 30) * i) * forward_left;
            // Player位置加v,就是射线终点pos
            Vector3 pos = startPos + v;
            // 创建射线
            Ray ray = new Ray(startPos, v);
            RaycastHit2D hitt = new RaycastHit2D();
            hitt =Physics2D.Raycast(startPos, v);
            Collider2D hitt_collider = hitt.collider;
            if (hitt_collider != null)
            {
                if (hitt_collider.CompareTag("Player") && hitt.transform != null)
                {
                    // 如果碰撞到什么东西,射线终点就变为碰撞的点了
                    pos = hitt.point;
                    print("x");
                }
                else
                {
                    pos = startPos + v;
                }
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

这是修改后的代码,之前的射线检测一直返回空引用的错误,后来在官网找到了答案:在执行碰撞检测之前判断一下检测结果是否为空,也就是if (hitt_collider != null)这行代码。
这个是回答的链接:
https://answers.unity.com/questions/641027/raycast-click-on-instance-object-reference-not-set.html?sort=votes

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/997478
推荐阅读
相关标签
  

闽ICP备14008679号