Is there a shorter way to code what I am trying to accomplish?

This is my code currently

            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.

1 Like

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.

Don’t know any other code for this but if I was you i just replace all “<” or “>” by “<=” and “>=”.

I don`t really know how this works exactly but I think you need this:

It clamps a variable between certain values

Vector3 currentPos = transform.position;

currentPos.x = Mathf.Clamp(currentPos.x, -10, 10);
currentPos.z = Mathf.Clamp(currentPos.z, -10, 10);

transform.position = currentPos;

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:

transform.position = someBoxCollider.bounds.ClosestPoint(transform.position);

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.

1 Like

This looks great! I will put it into practice tonight. Thank you very much for the added guidance so I don’t run around blind trying something new.