请问用Unity创建一个距离联合2d?的NullReferenceException

时间:2014-06-26 21:46:44

标签: unity3d

我正在尝试在扩展MonoBehaviour的脚本中创建一个Distance2dJoint。

不幸的是,我在这一行得到了NullReferenceException异常:

dj2d.connectedBody = otherBody;

我做错了什么?似乎dj2d为null,但是当我实例化它时怎么会这样呢?

void OnTriggerEnter2D( Collider2D other )
    {

        CatController otherCatController = other.GetComponentInParent<CatController> ();

        if ( otherCatController ) {
            Debug.Log("Hit a cat");
            if( otherCatController.index<index ){
                DistanceJoint2D dj2d = new DistanceJoint2D();
                Rigidbody2D otherBody = otherCatController.GetComponent<Rigidbody2D>();    
                dj2d.connectedBody = otherBody;

            }
        }

    }

1 个答案:

答案 0 :(得分:0)

我从统一论坛找到了解决方案......

            DistanceJoint2D dj2d = gameObject.AddComponent( "DistanceJoint2D" ) as DistanceJoint2D;
            dj2d.connectedBody = otherCatController.GetComponent<Rigidbody2D>();