- Home /
Adding joints through script
My question today is this, how does one go about adding a joint( in this case a fixed joint) through a script attached to the game object. My end goal is to allow objects to attach themselves to any object they collide with by joints Much thanks in advance
Answer by Maurice_B · Jan 02, 2015 at 08:56 PM
function OnCollisionEnter (collision : Collision)
{
if (collision.gameObject.GetComponent(RigidBody)!=null){
gameObject.AddComponent(FixedJoint);
gameObject.GetComponent(FixedJoint).connectedBody=collision.rigidbody;
}
}
// not tested but it should work.
good luck.
Maurice
Answer by MattyPhatty2x4 · Jan 03, 2015 at 11:02 AM
Can confirm this. Although i was getting really weird behavior with multiple objects due to multiple instances of a new joint forming. I added in a bool to prevent multiple creations of joints from the same object. Could probably come up with something better but this worked really well for me. Kinda Katamari Damacy like.
public class JoinObjects : MonoBehaviour {
bool hasJoint;
void OnCollisionEnter (Collision collision)
{
if (collision.gameObject.GetComponent<Rigidbody>() != null && !hasJoint) {
gameObject.AddComponent<FixedJoint> ();
gameObject.GetComponent<FixedJoint>().connectedBody = collision.rigidbody;
hasJoint = true;
}
}
}
thanks but I wrote my own for any one wanting it its in javascript #pragma strict
function Start () {
}
function Update () {
}
function OnCollisionEnter (collision : Collision)
{
if(collision.gameObject.GetComponent(Rigidbody))
{
var jointToAdd : FixedJoint;
jointToAdd = gameObject.AddComponent(FixedJoint);
jointToAdd.connectedBody = collision.gameObject.rigidbody;
}
}
I like this method,
How can I change the default parameters to my parameters I want such as setting the Spring to "100" after they collide ?
Your answer
![](https://koobas.hobune.stream/wayback/20220613175440im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to destroy linked components when object is destroyed? 1 Answer
Best practice for assigning class reference at runtime? 0 Answers
How to import the object from server to unity 2 Answers
Reseting Component/GameObject to its initial scene state. 4 Answers