Can't get platform to move to the other direction

This is my code:

using UnityEngine;
using System.Collections;

public class MovingPlat : MonoBehaviour {
	
	public static float movespeed = 2f;
	public Vector2 Direction = Vector2.right;

	public void Start(){

	}

	public void Update(){
		if (transform.localPosition.x == 40.5f)
			Direction = -Direction;

		if (transform.localPosition.x == 30.2f)
			Direction = Vector2.right;

		transform.Translate(Direction * movespeed * Time.deltaTime);
	}
}

Well yeah, I doubt that the x of the position of the transform is exactly 40.5 any time, unless set by you from code. Use a range, like position.x < 41 && position.x > 40 so it never changes direction and the default value of Direction is .right so it only moves in right.

Your localPosition.x value will never equal 40.5f. Floating point values are not exact, so what you call 40.5, a floating point register may store as 40.49999934. And the other problem is that you are not adding 1 bit of precision to the register every frame, so you’ll almost never even hit this number. You’d have to get very lucky for moveSpeed * Time.deltaTime to = 40.49999934 in the first place.

The solution is to check using >= (for the 40.5 case) and <= (for the 30.2 case) if that works for you. Or check localPosition.x is within 2.0 units of 40.5 (in other words >= 39.5 and <= 41.5). But in the latter case, you had better be sure that moveSpeed*Time.deltaTime will never be greater than 2.0 units in any single frame (you’d need to add code and add some hysteresis, say make sure it’s never greater than 1.9), or you’ll miss that window when they minimize the game or some other hiccup causes a delay making Time.deltaTime bigger than you expected.