当我试图写出游戏对象的标签时,为什么我会得到NullReferenceException呢?

时间:2015-08-06 15:41:13

标签: unity3d raycasting

我不知道为什么我会得到它。它只会在光线投射到达对象时弹出。

void Update(){
RaycastHit2D hitSideRight = new RaycastHit2D();
            hitSideRight = Physics2D.Raycast (transform.position, Vector2.right, 1.2f, 1 << LayerMask.NameToLayer("Ground"));
            Debug.DrawRay (transform.position, Vector2.right* 1.2f);

            RaycastHit2D hitSideLeft = new RaycastHit2D();
            hitSideLeft = Physics2D.Raycast (transform.position, -Vector2.right, 1.2f, 1 << LayerMask.NameToLayer("Ground"));
            Debug.DrawRay (transform.position, -Vector2.right* 1.2f);

            if(hitSideLeft.collider != null || hitSideRight.collider != null){
                CancelMove();
                Debug.Log(hitSideRight.collider.tag.ToString());
            }
}

我收到这行代码的错误(仅当光线与对象接触时):Debug.Log(hitSideRight.collider.tag.ToString());

2 个答案:

答案 0 :(得分:1)

替换||的{​​{1}},因为如果&& null且hitSideLeft为空,则条件为 true < / strong>你得到一个NullPointer

hitSideRight

答案 1 :(得分:1)

如果您想保留mean(age<=20)

,可以尝试此操作
||

但你应该知道...... RaycastHit2D col = hitSideLeft.collider ?? hitSideRight.collider; if(col != null){ CancelMove(); Debug.Log(col.tag.ToString()); } 返回Physics2D.Raycast(...)而不是bool

你的光线投射应如下所示:

RaycastHit2D