- Home /
Tidying up IF statements with '<' '>' in them
Hi there,
Im trying to tidy up a bunch of IF statements and I cant think of a way passed it due to the greater than and less than symbols. If anyone could offer any suggestions would be great! Here is my code:
if (transform.position.x > groundSizeX)
{
transform.position = updateX(-groundSizeX);
}
if (transform.position.x < -groundSizeX)
{
transform.position = updateX(groundSizeX);
}
if (transform.position.z > groundSizeZ)
{
transform.position = updateZ(-groundSizeZ);
}
if (transform.position.z < -groundSizeZ)
{
transform.position = updateZ(groundSizeZ);
}
Hi there, as a side note - the updateX and update Z code is as follow: Vector3 updateX(float x) { return new Vector3(x, transform.position.y, transform.position.z); }
Was thinking about maybe using ?? but not sure how that works...
Answer by Hellium · Oct 05, 2018 at 02:05 PM
void YourFunction()
{
Vector3 position = transform.position;
position.x = LoopValue( position.x, -groundSizeX, groundSizeX ) ;
position.z = LoopValue( position.z, -groundSizeZ, groundSizeZ) ;
transform.position = position ;
}
private float LoopValue( float input, float min, float max )
{
return input < min ? max : input > max ? min : input ;
}
Ah thanks so much man! Really trying to improve my code, but finding it hard to find alternative ways to do things!
I know the single question marks mean if but im not sure what the colon ':' means? Any chance you could describe that for us?
Thanks again!
var a = [what you are checking] ? [value if true] : [value if false];
In that function, the value if false
is another embedded comparison.
The conditional operator (?:), commonly known as the ternary conditional operator, returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
condition ? first_expression : second_expression;
The code return input < $$anonymous$$ ? max : input > max ? $$anonymous$$ : input ;
could have been translated as follow:
if( input < $$anonymous$$ ) return max;
else if( input > max ) return $$anonymous$$;
else return input ;
Your answer
![](https://koobas.hobune.stream/wayback/20220612175826im_/https://answers.unity.com/themes/thub/images/avi.jpg)