Unity3d 如何使用Unity创建二维距离关节?NullReferenceException

Unity3d 如何使用Unity创建二维距离关节?NullReferenceException,unity3d,Unity3d,我试图在一个脚本中创建一个Distance2dJoint来扩展monobhavior 不幸的是,我在这一行收到NullReferenceException异常: dj2d.connectedBody = otherBody; 我做错了什么?dj2d似乎是空的,但当我实例化它时,它怎么可能是空的呢 void OnTriggerEnter2D( Collider2D other ) { CatController otherCatController = other.Ge

我试图在一个脚本中创建一个Distance2dJoint来扩展monobhavior

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

dj2d.connectedBody = otherBody;
我做错了什么?dj2d似乎是空的,但当我实例化它时,它怎么可能是空的呢

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;

            }
        }

    }

我从unity论坛找到了解决方案

            DistanceJoint2D dj2d = gameObject.AddComponent( "DistanceJoint2D" ) as DistanceJoint2D;
            dj2d.connectedBody = otherCatController.GetComponent<Rigidbody2D>();
可能重复的