Movement reacting when

Im trying to have an object move back and forth, ofc when it hits something i need it to start moving the other direction, which is where I have a problem, im trying to create a stuck boolean if its X pos is the same as its last X pos, so when its “stuck” it will move the other way, if someone could tell me what in my code is wrong, ive a feeling its the if statements but not sure

var forwardspeed : float;
var backwardspeed : float;
var Currentpos : float;
var Stuck : boolean;
var forwardmoving : boolean;

function Update ()
{
	if(transform.position.x == Currentpos)
	{
	Stuck=true;
	}
	else
	{
	Stuck=false;
	}

	if(Stuck == false)
	{
		if(forwardmoving == true)
		{
		rigidbody.AddForce(Vector3(forwardspeed,0,0));
		}
		if(forwardmoving == false)
		{
		rigidbody.AddForce(Vector3(backwardspeed,0,0));
		}
	}
	
	else if(Stuck == true)
	{
		if(forwardmoving == true)
		{
		rigidbody.AddForce(Vector3(backwardspeed,0,0));
		forwardmoving = false;
		Stuck = false;
		}
		if(forwardmoving == false)
		{
		rigidbody.AddForce(Vector3(forwardspeed,0,0));
		forwardmoving = true;
		Stuck = false;
		}
	}
}

function LateUpdate ()
{
	Currentpos = transform.position.x;
}

I dont think that the above approach is the best one. You will probably never get the variable stuck to change because the object is continously applying force and it rebounds. What you see is not it keeps on walking into the object, its rebounding and then undergoing a forward force again and again rapidly over very small distances and looks like its at the same spot.

You can use transform.Translate as it is not time dependent but I doubt that even that will work.

But if I were you, I would go for raycast, it works 100%. You will have to have two rays, one at the front, one at the back, and the only change in the logic will be that you will have to change the direction of motion when the point where the ray collides with the object is very near, like 0.05 units of something, that means it has almost collided and it turns back. The advantage of this method is that it can be expanded to do many other functions later if you want and is much more hassle free. Remember you dont always have to check for physical collisions, because physical collisions are detected only 50 to 60 times per second ( that is your frame rate BTW).

I Hope this helps! If you want to do it the raycast way, then you can check out the scripting manual itself, it has all the things you need for this and is written in a clear manner.