Reset the position of a GUI.Button

Hello, I want to have a dynamic GUI.Button moving from left to right and back again. In my code when i click on a Button it is moving left to right and from right back again to it’s original position on left, but then when the Button is on it’s original position suddenly it is not moving again. The problem is probably that my Button is not reseting it’s position, could you help me with that pls ?

function Update () {
	if (moveOut) {
		
		if (itemRect.x != positionX) {
			itemRect.x = Mathf.MoveTowards(itemRect.x, target, speed * Time.deltaTime);	
		}else {
			moveOut = false;
		}
	}
	
	if (moveIn) {
		
		if (itemRect != originalX) {
			itemRect.x = Mathf.MoveTowards(itemRect.x, originalX, speed * Time.deltaTime);	
		}else {
			moveIn = false;
		}
	}
	
	if (Input.GetButtonUp("Jump")) {
    	moveIn = true;
        moveOut = false;
    }
}

function MyWindow() {
    if (isWindowOpen) {
       if (GUI.Button (itemRect,"Item")) {
	  print("Item clicked");
	  moveOut = true;	
					
	}
    }
}

function OnGUI () {
   MyWindow();
}

Since itemRect.x is a floating point number, it may never reach an exact value. For example, if you’re aiming for 0.0, it might end up being 0.00000001. It’s a good practice to test against a threshold instead of testing equality.

Instead of:

    if (itemRect != originalX) {...}

Try (as one possible solution):

    var threshold = 0.001;
    if (Mathf.Abs(itemRect.x - originalX) < threshold) {...}

Thank you sir, your solution works. I always wondered how and where i could use Mathf.Abs now I am using it hurray :slight_smile:

if (moveIn) {
		var threshold = 0.001;
		
		if (Mathf.Abs(itemRect.x - originalX) > threshold) {
			itemRect.x = Mathf.MoveTowards(itemRect.x, originalX, speed * Time.deltaTime);
		
		}else {
			moveIn = false;
		}
	}