- Home /
Spawning GameObjects with Hinge Joints
Hi everyone,
I'm working on a level generator for an endless runner and I want to spawn some prefabs with hinge joints.
The trouble is that when I spawn an object with a hinge joint, it retains the anchor and connected anchor from when the prefab was saved, not relative to its spawned position.
Any idea how I can fix this?
hi sir, am facing problem on adding hinge joint to my prefab. what my project i need to create rope that was dynamically increasing and decreasing when we press up and down arrows. what am doing is
//instantiating a prefab
clone = (GameObject)Instantiate (obj, current.transform.position, Quaternion.identity);
//storing the prefab into a list
instantlist.Add(clone);
instantlist[instantlist.Count-1].name="clone"+instantlist.Count;
//adding hinge joint
clone.AddComponent(); clone.GetComponent
//assaign position
clone.transform.position = new Vector3 (current.transform.position.x, current.transform.position.y+1f , current.transform.position.z);
current = clone.gameObject.transform;
Another option is to use a Rigid Body (IsKinematic=true) as parent and set the Connected Rigid Body property to this. Spawning the parent keeps the Connected Anchor in place and it works without any glitches. I found this solution on https://stackoverflow.com/questions/22845379/unity-spawning-gameobjects-with-hinge-joints
Answer by sampenguin · Apr 15, 2014 at 02:37 AM
I am spawning a hinge joint object from a prefab and it works OK, provided you connect to the other rigid body after instantiation.
objectBwithHingeJoint = GameObject.Instantiate(hingeJointPrefab, objectA.hingeJointSpawnOffset.transform.position, Quaternion.identity) as GameObject;
HingeJoint hj = objectBwithHingeJoint.GetComponent<HingeJoint>();
hj.connectedBody = objectA.rigidbody;
You should also be able to adjust the anchor properties via script at this point.
Also I found early on that nesting an object with a hinge joint inside the object its attaching to caused lots of problems. So I spawn them both independently (with B getting its initial position from a dummy transform inside of A) and attach via script, as you can see above.