I want to move a cube using a GUI button in C#

I would like to move a cube up the Y-Axis when a GUI button has been pressed.

I would like the the Cube to move back down the Y-Axis to its original position when the same button has been pressed.

I am struggling to understand how to do this task and would like some advice on how to go about setting something like this up.

Thank You.

attach this script to the cube and try it out.

#pragma strict

private var oPos : Vector3;
public var speed = 10;
private var move = false;

function Start () {
	oPos = transform.position;
}

function Update () {

}

function OnGUI() {
	if ( GUI.Button(Rect(50,50,100,50), "Click me") ) {
		move = !move;
	}
	
	if ( move ) {
		transform.position = Vector3.Lerp(transform.position, transform.position + Vector3.up, Time.deltaTime * speed);
	} else {
		transform.position = Vector3.Lerp(transform.position, oPos, Time.deltaTime * speed);
	}
}

edit: just saw you wanted C# in the title…

using UnityEngine;
using System.Collections;

public class YMover : MonoBehaviour {

	private Vector3 oPos;
	public int speed = 10;
	private bool move = false;
	
	void Start () {
	    oPos = transform.position;
	}
	
	
	void OnGUI() {
	    if ( GUI.Button(new Rect(50,50,100,50), "Click me") ) {
	        move = !move;
	    }
	
	    if ( move ) {
	        transform.position = Vector3.Lerp(transform.position, transform.position + Vector3.up, Time.deltaTime * speed);
	    } else {
	        transform.position = Vector3.Lerp(transform.position, oPos, Time.deltaTime * speed);
	    }
	}
}

That was the sort of thing I was looking for. Thank You adnan.e94 :smile:

How do I make it so that the cube doesn’t continue up the Y-Axis forever when I press the button?

So for example:

  • I press the button,
  • The cube moves up the Y-Axis for a certain distance and then stops.
  • The cube doesn’t move again until I press the button.
  • Pressing the button will move the cube down the Y-Axis back to its original position.

change the moveDistance var depending on how much you want it to move.

using UnityEngine;
using System.Collections;

public class YMover : MonoBehaviour {

	private Vector3 oPos;
	public int speed = 10;
	public int moveDistance = 10;
	private bool move = false;
	
	void Start () {
	    oPos = transform.position;
	}
	
	
	void OnGUI() {
	    if ( GUI.Button(new Rect(50,50,100,50), "Click me") ) {
	        move = !move;
	    }
	
	    if ( move ) {
	        transform.position = Vector3.Lerp(transform.position, oPos + Vector3.up * moveDistance, Time.deltaTime * speed);
	    } else {
	        transform.position = Vector3.Lerp(transform.position, oPos, Time.deltaTime * speed);
	    }
	}
}

Thank You again :smile:

Could i bind that to a cube to move a door? So like when i click a cube the door goes down?