- Home /
C# Rotate GameObjects Regardless of List Size
I have a script that rotates gameobjects in opposite directions. However I can only get a maximum of four gameobjects to rotate. So when for example I add six gameobjects to gameObjectList the last two gameobjects don't rotate. Is there a way I can get my script to rotate all of the gameobjects within gameObjectList regardless of list size?
for (int i = 0; i < gameObjectList.Count -1; i+= gameObjectList.Count/2){
gameObjectList[i].Rotate( Vector3.forward, - fSpeed / fDistance);
gameObjectList[i+1].Rotate( Vector3.back, - fSpeed / fDistance);
}
for (int i = 0; i < gameObjectList.Count -1; i+= gameObjectList.Count/2)
Are you sure this is correct ?
Try this:
for (int i = 0; i < gameObjectList.Count -1; i= i+2) {
...
If gameObjectList.Count is 1, then it will not rotate at all with that loop.
Answer by SnotE101 · Dec 23, 2014 at 07:19 PM
Beans, I believe your problem lies in your for loop. i < gameObjectList.Count - 1' This will stop the loop at the second to last object in your list. If your list has six objects and you add 3 to each object in your code
i+= gameObjectList.Count/2` then your final line gameObjectList[i+1].Rotate( Vector3.back, - fSpeed / fDistance);
adds another int those three making it only rotate 4 objects. I hope this helps. I would suggest using a normal for loop. for(int i = 0; i < gameObjectList.Count; i++)
Good Luck!
Any suggestions for how I could reach the next gameObject in gameObjectList? i+1 was how I reached the next gameObject and had it rotate in the opposite direction of i. If I use a normal for loop i+1 doesn't exist.
@Adre76. It is interesting, how are your comment differs from $$anonymous$$e, except time?
Answer by DanSuperGP · Jan 08, 2015 at 12:23 AM
Rather than playing silly games with your loop counters, why not just do a regular loop, and just flip the direction every other step.
float direction = 1.0f;
foreach(GameObject go in gameObjectList)
{
go.Rotate( Vector3.forward * direction, - fSpeed / fDistance);
direction *= -1.0f;
}
Your answer
Follow this Question
Related Questions
C# GameObject Reverses Z Rotation 0 Answers
C# Preserving GameObjects' Previous Meshes 1 Answer
C# Gameobject Rigidbody Mouse Collision 1 Answer
C# Child GameObject Disabled Script SetActive(false) 1 Answer
C# Plane Detecting a Gameobject 1 Answer