0

I am trying to create a Distance2dJoint inside a script that extends MonoBehaviour.

Unfortunately, I am getting NullReferenceException exception on this line:

dj2d.connectedBody = otherBody;

What am I doing wrong? It seems that dj2d is null, but how can that be when I have instantiated it?

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;

            }
        }

    }
Ginger
  • 8,320
  • 12
  • 56
  • 99
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeSmile Feb 16 '15 at 10:44

1 Answers1

0

I found the solution from the unity forums...

            DistanceJoint2D dj2d = gameObject.AddComponent( "DistanceJoint2D" ) as DistanceJoint2D;
            dj2d.connectedBody = otherCatController.GetComponent<Rigidbody2D>();
Ginger
  • 8,320
  • 12
  • 56
  • 99