Check to see if integer is between two others

Is there a more efficient way to check to see if a value is bewteen to other values than doing :

if(scrollPosition.x > Screen.width*.25 && scrollPosition.x < Screen.width *.49 || scrollPosition.x < Screen.width*.01 &&  scrollPosition.x > Screen.width*.25){

it would be nice if you could do something like

if(Scroll.position.x.isBetween(.25, .49 || .01, .25)){

Is it possible to create a function like this? Thanks for any help.

You’re not asking about integers…integers are whole numbers and don’t have fractions. Anyway, you can make a function, but it will be less efficient because of the overhead involved in calling a function. What you wrote first is probably the most efficient way it can be done, since the compiler will short-circuit conditions where appropriate. For example, if scrollPosition.x is less than Screen.width*.25, it won’t bother evaluating the next condition, since the first one already failed.

If you’re talking about “more efficient” in terms of less code, rather than fastest speed, then you can make a function by passing in those parameters, but you can’t use “||” in the parameters like that. Pass them in normally, and use && and || as appropriate in the code inside the function.

Of course. :slight_smile: It isn’t possible to declare a function that looks exactly like what you have above, however, because of 2 things:

  1. position.x is a float, and you can’t extend a float to include a new method.
  2. “||” is an operator that, after evaluation of first the left-hand side and then, if necessary, the right-hand side, returns a boolean. So what you have above would mean that isBetween is a method on a float, that takes a boolean parameter, which isn’t very useful. :wink:

What you need is a method that takes a single float, and then a variable number of sets of floats, in between which you want the first one to be. You can accomplish that with the params keyword. It allows you to declare methods with a variable amounts of arguments. Like this:

private bool isBetween(float input, params Vector2[] intervals)
    for (int i = 0; i < intervals.Length; i++)
        if (input > intervals_.x && input < intervals*.y)*_

return true;

return false;
This method can be called like so:
isBetween(scrollPosition.x, new Vector2(Screen.width * .25f, Screen.width * .49f), new Vector2(Screen.width * .01f, Screen.width * .25f));
The use of a Vector2 might seem odd. I chose it because it helps force the user to always supply sets of two floats. If I had declared the method to only take params float[], the caller could supply an uneven amount of floats, which wouldn’t make sense for this particular scenario. If you can make sure the method is never called with an uneven number of floats, it can be modified to make the line of code that calls it look simpler. I think I’ll leave that task to you. :wink: