- Home /
For loop not running correctly inside start ()
I Am trying to run through an array of game objects and make the first item be the "leader" then for the rest of the items in the array assign different positions depending on the index value the else part of the for loop is not executing i also tried use another if and an else if that contain (2%!=0) but still no luck`void Start () {
GameObject[] fighters;
fighters = GameObject.FindGameObjectsWithTag ("Fighter");
//set leader trasform to nothing on first item in arry witch is the leader
fighters [0].GetComponent<formation> ().leader = null;
for (int i=0; i < fighters.Length; i++) {
//set the item on indexzero to be the leader of all other items in arry
//the +1 is to skip the first elment which is the leader
fighters [i + 1].GetComponent<formation> ().leader = fighters [0].transform;
//assighn items dpending on index number to diffrent postion each time the for loop runs
if (i % 2 == 0) {
fighters [i].GetComponent<formation> ().setSide = setSide;
setSide = setSide + 7;
} else {
fighters [i].GetComponent<formation> ().setSide = setSide;
setSide = setSide - 7;
}
}
}`
been working at it for hours dont know what i'm doing wrong
If the else part is not being executed, it could be that your fighters array is only one element long. You could use Debug.Log to print out and verify the length of fighers.
One other thing that should crash your loop is that you let your i run up to Length-1, but then access fighers[ i + 1 ], which would be fighers[ Length ] and is hence out of bounds of your array.
i fixed it so its length+1 but still getting the same problem the fighters assigned -7 just all equal to 0 ins$$anonymous$$d of -7 -14 - 21 etc this are the results i am expecting on each item in the array for its setback value 0,7,-7,14,-14,21 ,-21 etc but i am getting 0,7,0,7,0
Answer by Nanity · Jul 08, 2013 at 08:22 AM
Still not sure what you want to achieve with your code, but from your description of the numbers I can see the issue, in one cycle you are adding +7 in the next you add -7, so you're at the beginning (0).
Correct code:
if
(i % 2 == 0) {
fighters [i].GetComponent<formation> ().setSide = -setSide;
setSide += 7;
} else {
fighters [i].GetComponent<formation> ().setSide = setSide;
}
thanks a bunch it seems so obvious now thanks heaps !! i had to move the setSide += 7; out side of the if tho and start my i=1 and it did what i wanted it to
Your answer
![](https://koobas.hobune.stream/wayback/20220613105635im_/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
Problem with array on gameobjects 2 Answers
How can I code a pattern detector in an array of integers? 1 Answer
I have never seen a null reference exception like this one! 1 Answer
NullReference when accessing GameObject in array (C#) 1 Answer