Hello everyone!
So I’m trying to connect bones with a Spring joint using a script. so I don’t have to manually do it.
But for some reason I my script can only connect the elements that are before the bone I want to set the Joints for (or it can also connect it to itself).
It’s very weird, I cannot wrap my head around why it doesn’t work, hwere is the code:
[
int counter = 0;
Component[] bones2 = GetComponentsInChildren < Transform > ();
List < Component > bones = bones2.ToList();
bones.RemoveAt(0); //Removes the first element that is for some reason the parent
foreach(Component bone in bones) {
if (bone.transform.childCount == 0) {
SpringJoint2D spring1 = bone.gameObject.AddComponent(typeof (SpringJoint2D)) as SpringJoint2D;
SpringSetter(spring1);
spring1.connectedBody = bones[counter - 1].GetComponent < Rigidbody2D > ();
} else if (counter - 1 == -1) {
SpringJoint2D spring1 = bone.gameObject.AddComponent(typeof (SpringJoint2D)) as SpringJoint2D;
SpringSetter(spring1);
spring1.connectedBody = bones[counter + 1].GetComponent < Rigidbody2D > ();
} else {
SpringJoint2D spring1 = bone.gameObject.AddComponent(typeof (SpringJoint2D)) as SpringJoint2D;
SpringSetter(spring1);
spring1.connectedBody = bones[counter - 1].GetComponent < Rigidbody2D > ();
SpringJoint2D spring2 = bone.gameObject.AddComponent(typeof (SpringJoint2D)) as SpringJoint2D;
SpringSetter(spring2);
spring2.connectedBody = bones[(counter + 1)].GetComponent < Rigidbody2D > (); //This line refuses to work! It always keeps it null
Debug.Log(bones[counter + 1].gameObject.name);
}
counter++;
}
private static void SpringSetter(SpringJoint2D spring1) {
spring1.frequency = 8 f;
spring1.dampingRatio = 0.8 f;
}
Any help is apprechiated. This script simply refuses to get the bones[counter+1] element