if ( transform.position.x > 10f )
transform.position = new Vector3(10f, transform.position.y, transform.position.z);
else if ( transform.position.x < -10f )
transform.position = new Vector3(-10f, transform.position.y, transform.position.z);
if ( transform.position.z > 10f )
transform.position = new Vector3(transform.position.x, transform.position.y, 10f);
else if ( transform.position.z < -10f )
transform.position = new Vector3(transform.position.x, transform.position.y, -10f);
I just want to know if X is greater or less than Y, set X to Y. I am curious if there is a more efficient way to code this, as this is on a game object that there will be thousands of laying around.
I often run into similar questions, but I am new to unity so hopefully some unity gurus can clarify;
By instinct I would think it’s probably a few cycles faster to get the vector3 transform.position before you do the if’s - that way you only need to access the transform component once each iteration. It would also be a bit cleaner code.
Oh right! That little bit will help a lot actually. And yea, being new to this all it’s sometimes hard to know if there are built-in shortcuts / faster ways of doing certain actions. I always find that to be half the fun when learning a new game engine.
Note that if you’re moving with physics (rigidbody.AddForce or something like that), this will cause the player to stutter near the ± 10 mark.
If you want a more general solution, you could place a box collider around the area you want your transform to be in. Then, you can simply ensure that you’re within that box’s bounds:
The bounds are axis-aligned, so this only works well if the box collider is axis aligned too - which means that it’s rotations is in multiples of 90.