Stop transform.position by collider

Hi all, Is there any way to stop an object from going further by a collider even if the script makes its position update every frame to increase?
Like this:

transform.position = new Vector2(100, transform.position.y);
How to stop it from going to 100 if there is a collider in between?

Give your GameObject a Rigidbody and perform a SweepTest.

var rb = GetComponent<Rigidbody>();

var distance = 100f;
RaycastHit hit;
if (rb.SweepTest(direction, out hit, distance))
  distance = hit.distance;
transform.Translate(direction * distance);

As you can see, you need to specify a direction rather than a target position, as your collision test is based on going a direction rather than arriving at a position (“if there is a collider inbetween”).

If needed, you can calculate the direction by subtracting the current position from the targetPosition:

var direction = targetPosition - transform.position;

By the way, if your object does not have a collider but rather is a point, replace the SweepTest with a regular Raycast and don’t add a Rigidbody.