- Home /
For loop not working?
I am trying to make a script that will add and edit hinge joints to every object in the scene with the tag "force". I have rewritten this script multiple times, and now it has stopped working completely. Here is the code-
var forces : GameObject[];
function Update () {
forces = GameObject.FindGameObjectsWithTag("force");
if(Input.GetKeyDown("l")) {
Gotoedit ();
}
}
function Gotoedit () {
for(var i = 0; !i == forces.length; i++){
GameObject.FindGameObjectWithTag("fuse").AddComponent(Rigidbody);
forces[i].AddComponent(Rigidbody);
forces[i].AddComponent(HingeJoint);
forces[i].GetComponent(HingeJoint).connectedBody = GameObject.FindGameObjectWithTag("fuse").rigidbody;
forces[i].GetComponent(HingeJoint).spring.damper = Mathf.Infinity;
}
}
I moved all the forces[i] statements to the function Update (), and them it worked fine with one GameObject, so I know it't not the AddComponent/GetComponent. I tried adding a debug in the Gotoedit, so I know that it is being called when I press the L key. This leaves the FOR statement, which i'm assuming is the problem. I'm fairly new to FOR statements (not javascript), so I came here to get advice. Does anyone have ideas?
*Javascript only, duh
*Thanks!
Answer by StormSabotage · Feb 01, 2014 at 05:21 PM
for(var i = 0; !i == forces.length; i++){
my god...
for(var i = 0; i <= forces.length; i++){
take and please learn Javascript and "for" cycle syntax
btw if you want to know when "A" not equals "B" you should write this:
if(A != B)
not
if(!A == B)
Thanks, I haven't taken classes on Unity, I've been $$anonymous$$ching myself in my spare time. Thanks!
GameObject.FindGameObjectWithTag("fuse").AddComponent(Rigidbody);
that's wrong string in your cycle, it will try to add Rigidbody to same GameObject every turn... do that on Start() function.
forces = GameObject.FindGameObjectsWithTag("force");
If your "forces" GameObjects always same you no need to re-assing variable every frame on Update(), move it to Start()