我正在尝试在扩展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;
}
}
}
答案 0 :(得分:0)
我从统一论坛找到了解决方案......
DistanceJoint2D dj2d = gameObject.AddComponent( "DistanceJoint2D" ) as DistanceJoint2D;
dj2d.connectedBody = otherCatController.GetComponent<Rigidbody2D>();