- Home /
Attaching rigidbody to a HingeJoint via C#
Hello,
Is there a way to attach a rigidbody to a HingeJoint in C#? I tried setting the rigidbody to HingeJoint.rigidbody (i.e. _hingeJoint.rigidbody = _objectTobeAttached.rigidbody), but it says that HingeJoint.rigidbody is read only.
Thanks!
Answer by clunk47 · May 05, 2014 at 04:10 PM
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(HingeJoint))]
public class Example : MonoBehaviour
{
HingeJoint joint;
//Assign in inspector while keeping variable private.
[SerializeField] Rigidbody cBody;
void Awake()
{
if (!joint)
joint = GetComponent<HingeJoint>();
else
{
if (!cBody)
joint.connectedBody = cBody;
}
}
}
And the trick here is, look at the Hinge in the Inspector. You (OP) were using rigidbody=
, but you can see that Inspector slot is labelled ConnectedBody
, as Clunk has in the example.
Then, if you look at the scripting docs for hinge: http://docs.unity3d.com/Documentation/ScriptReference/HingeJoint.html you'll see the official name. If you click on that, it gives a tiny example (some are great, some don't have examples, the one for connectedBody is so-so.) Sometimes if you look for similar things, like springs, you'll find better examples.
What did you mean by " Assign in inspector while keeping variable private." ? assign what in inspector?
Your answer
Follow this Question
Related Questions
Hinge joints disconnect when pulled too far. 0 Answers
Hinge Joint goes crazy 1 Answer
How to rotate rigidbody relative to jointed other rigidbody? 2 Answers
hinge joints and velocity 1 Answer