- Home /
Array problems
Hi
I'm having some trouble understanding the use of arrays(or lists?). For an example i have 2 different arrays with Transforms called slaves[] and masters[]. I want to get the angle between the slave and master and afterwards i want to add torque to a rigidbody, i could do it manually like this: AngleError[1] = Vector3.Angle(slave[1].up,master[1].up); slaveRigidbody[1].AddTorque(slave[1].right*AngleError[1]); and go on: AngleError[2] = Vector3.Angle(slave[2].up,master[2].up); slaveRigidbody[2].AddTorque(slave[2].right*AngleError[2]); and so on...
But with 12 different masters and slaves it's pretty time consuming. Is there a way to make this happen with only a single piece of code instead of 12?
Thanks in advance :)
Answer by Suley · Mar 13, 2017 at 08:53 AM
Hi,
as far as i understand u want to do this in a loop, so u dont have to type the 12 iterations. So it will be something like this.
for (int i = 0; i <= AngleError.Length; i++)
{
AngleError[i] = Vector3.Angle(slave[i].up,master[i].up);
slaveRigidbody[i].AddTorque(slave[i].right*AngleError[i]);
}
Note if u use List u need AngleError.Count;
If i understood ur Question wrong, sorry for the misunderstanding
Answer by Namey5 · Mar 13, 2017 at 08:51 AM
Rather than using a ForEach loop, simply use a For loop. A For loop is a loop which simply runs the same piece of code over and over again, passing that code a variable. The loop continues, increasing the variable each time until it reaches a set maximum. You can use for loops for different things, but that's the main way you would use it. So, in this case it would be;
for (int i = 0; i < slave.Length; i++)
{
AngleError[i] = Vector3.Angle(slave[i].up,master[i].up);
slaveRigidbody[i].AddTorque(slave[i].right*AngleError[i]);
}
And btw, arrays start at 0, not 1.