- Home /
Prefabs can't be attached together with a hinge joint (A joint can't connect the body to itself)
I am trying to create a script that generates a rope attached to a designated anchor point when a player hits it with a grapple projectile.
To do this, I instantiate 8 separate GameObjects of the same prefab ("rope") and then use a HingeJoint to connect each gameObject to the previous rope.
public class Anchor : MonoBehaviour
{
public GameObject rope;
private Vector3 ropeSeparationDistance = new Vector3(0, 0.4f, 0);
private Vector3 initial;
private int size = 8;
void Start()
{
//Get anchor's position
initial = transform.position;
//Placing 8 of the rope prefab into a list
List<GameObject> ropes = new List<GameObject> { rope, rope, rope, rope, rope, rope, rope, rope };
//Creating a single rope piece that is connected to the anchor, this part works fine
Instantiate(ropes[0]);
ropes[0].transform.position = initial - ropeSeparationDistance;
ropes[0].GetComponent<HingeJoint>().connectedBody = gameObject.GetComponent<Rigidbody>();
//Create 7 more ropes, each connecting to the previous Rope
for (int i = 1; i < size; i++)
{
Instantiate(ropes[i]);
ropes[i].transform.position = initial - (ropeSeparationDistance * (i + 1));
ropes[i].GetComponent<HingeJoint>().connectedBody = ropes[i - 1].GetComponent<Rigidbody>();
}
}
}
When I run the script, it creates all 8 ropes just fine, but for some reason, each rope's connectedBody is set to the GameObject my script is attached to. I am given the error "A joint can't connect the body to itself". I will note that I've checked my rope prefab and it by default does not contain a connectedBody. I've tried checking and unchecking "Auto Configure Connect" but to no avail. Am I missing something logic wise? Or do I just not understand how prefabs interact with the HingeJoint connectedBody property?
Answer by Kobakat · Mar 04, 2020 at 07:04 AM
I was able to solve my own problem here. I made a simple logic error by putting the same rope object into a list, then instantiating the same rope (although at different indices) with these lines of code. To help those that may make the same mistake in the future, here was my solution.
List<GameObject> ropes = new List<GameObject>();
//Placing 8 of the rope prefab into a list
for (int i = 0; i < size; i++)
{
ropes.Add(Instantiate(rope));
}
Your answer
Follow this Question
Related Questions
Camerascript works strange! 0 Answers
Human model clothes 1 Answer
Raycast from one camera using a gameobject relative to another camera 1 Answer
3D rotation in 3 components 2 Answers