Why Can't I Move In Just X?

I have this setup so that I click an object, and my character runs to it to hide behind it. This line of code works, except that it lines up their transforms perfect, which is bad, because it picks my character up and makes him float. It’s a side scroller, so I need to move him in just the X until the position.x of both objects match. However, when I add the position.x to these values I get all kinds of errors. It seems to me like I’m missing something simple, but I can’t seem to figure it out. Any help? Thanks.

if(hidingSpot != null)
		{
			transform.position.x = Vector2.MoveTowards(transform.position.x, target.transform.position.x, speed);
		}

The code above only works if I remove the “.x” from each of the positions. So if I do that, then how to I specify I only want the X position?

Vector2.MoveTowards gives you a Vector2, not a float.
Besides, it takes two Vector2, not two floats.

transform.position=new Vector2(Vector2.MoveTowards(transform.position, target.transform.position, speed).x,transform.position.y);

or you could use Mathf.MoveTowards, which takes and gives floats.

transform.position=new Vector2(Mathf.MoveTowards(transform.position.x, target.transform.position.x, speed), transform.position.y);

You can’t assign transform.position.x alone.

Vector2s are structs, not classes. Ie: Structs are value types, not reference types. Which means that when you get the position from a transform, you are getting a COPY of the Vector2. Changing that x doesn’t make sense because you’re changing the x of a copy, not affecting the transform at all.

// Make a copy
Vector2 newPosition = transform.position;
// Change the copy
newPosition.x = Mathf.MoveTowards(transform.position.x, target.transform.position.x, speed);
// Override transform's position with our copy's values.
transform.position = newPosition;

EDIT: Changed code to Mathf.MoveTowards.

Ah thanks! The Mathf.MoveTowards makes more sense to me, so I used that one and it works perfectly. Thanks for the help and for answering so quickly.