Can i do any cool tricks with <>= operators?

if(pos.x >= 0 && pos.x <=1 && pos.y >= 0 && pos.y <=1)

My instincts say this is unwieldy. I’m probably wrong, but two checks each to see if values fall within a range seems odd. there has to be a better way to do this

Can i do something like if(0<pos.x<1)
is there any other way to shorten this down a little? would it make it anymore efficient?

if (new Rect(0, 0, 1, 1).Contains(pos))

Bear in mind that the if statements are faster, since that’s what Rect.Contains is doing anyway, so the same work is being done plus the function call overhead (and making a new Rect). The exact code for Contains is:

public bool Contains (Vector2 point)
{
    return point.x >= this.xMin && point.x < this.xMax && point.y >= this.yMin && point.y < this.yMax;
}

–Eric

2 Likes

Nope, there is no cool syntax sugar for any of those operators.

The operators really just translate to static function calls. The functions that are defined on the types being compared, if you’ve ever set up operator methods:

http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

Yes, that link is for an old version of .Net… well that’s because operator overloading really hasn’t changed at all since. And because it’s really just a 1 to 1 conversion of the operator to a function call, there’s not a lot of tricks you can do with it.

What you can do is write your own static functions that test what you want.

For instance an ‘InRange’ function that takes 3 values, value, max, min, and returns if the value is between max and min:

        public static bool InRange(float value, float max, float min)
        {
            return (value >= min && value <= max);
        }

I have all sorts of methods like that here:

https://code.google.com/p/spacepuppy-unity-framework/source/browse/#svn%2Ftrunk%2FSpacepuppyBase%2FUtils