Hi, scripting noob question here: I have a scene where my camera.position.y freely pans up and down. I need to set a ‘phase’ integer when the camera is within a certain range of editPoints in an array.
for example:
editPoint[0] = 10;
editPoint[1] = 20;
editPoint[2] = 30;
I know there must be a cleaner way of writing code than using a bunch of ‘if’ statements to set my ‘phase’ integer. Can I use a for loop? How?
if (cam.position.y > editPoint[0] && cam.position.y < editPoint[1]) phase = 0;
if (cam.position.y > editPoint[1] && cam.position.y < editPoint[2]) phase = 1;
if (cam.position.y > editPoint[2] && cam.position.y < editPoint[3]) phase = 2;
Any help is appreciated. Thanks!
What you do is use an index in the for loop to scan all values looking to see if the value in question fits in the interval.
Notably,the for loop does NOT iterate over all points, but rather all points minus one, because it has to compare between two values, this one and the next.
For your case it’s something like this:
float[] editPoint = new float[] {
10, 20, 30};
float ValueToTest = 1.0f; // insert your camera Y value here?
int phase = -1; // undefined
for (int i = 0; i < editPoint.Length - 1; i++)
{
if (ValueToTest >= editPoint[i] && ValueToTest < editPoint[i + 1])
{
phase = i;
break;
}
}
// if phase is not -1 then you found a valid editPoint[] array value
(caveat, I didn’t test this code…
)
Also, note that usually you use >= for the lower bounds, and < for the upper bounds. This is generally a common convention I follow, but there could be a case for other comparison operators which would change the nature of the returned value.
2 Likes
It works perfectly! ThankYou.
1 Like