- Home /
Question by
rohanbanerjee · Jun 17, 2015 at 07:40 PM ·
c#rigidbody2dhingejoint2dconnectedbody
How to set the "Connected Body" of a HingeJoint 2D using Script?
At first, I add the hingejoint 2d component to the gameobject. Then, I have a prefab, I instantiate it and want to assign its rigidbody 2d component to the connected body of the hingejoint 2d. Iam unable to do this. I read all the documentation as well as the blogs. Please help. Here's the code.
//Boxnew is the prefab, I want its rigidbody component
GameObject box2 = (GameObject)Instantiate (boxnew);
//Now I attach hingejoint to my gameobject, works fine
hingenew = gameObject.AddComponent<HingeJoint2D>();
hingenew.GetComponent<HingeJoint2D>().connectedBody = box2.rigidbody2D;
//Error Above
//Error: InvalidCastException: Cannot cast from source type to destination type.
Iam unable to set the connected body at runtime. Literally gave up.
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613201112im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Non-Static Member Rigidbody2D.MovePosition 1 Answer
NavMesh with custom movement 0 Answers