How do I make an object move when I click a GUI button? I want the object move upward.

How do I make an object move when I click a GUI button? I want the object move upward.

A lot of ways can be used to achieve that. The goal you have in mind will eventually be the base of how you decide on continuing I guess.

Because I’m unsure of how far you’ve progressed in your attempt I wrote a little more than needed probably. Than again better to be on the safe side of things.

First thing you’ll need to add a reference from whatever you’re using to handle your button towards the object you’re moving. Again more than one solution to this but the simplest would be something like the below.

using UnityEngine;
using System.Collections;

public class GUIscript : MonoBehaviour {

	public GameObject objectToMove;
	
}

This will enable you after finishing the script to drag the object you want moved into the slot created for that in your Inspector panel.

After that a couple of things are possible to extend this mini script with. Feel free to just copy paste this and uncomment the options as you test out what suits your needs the most. (don’t forget the comment out the others while doing so of course)
For the example below I just used a cube (don’t forget to give it a rigidbody, and select use gravity or not depending on the setting you’re in, if you’re recreating this with just a cube in a blank scene than make sure to switch the use gravity option off in the inspector)

using UnityEngine;
using System.Collections;

public class GUIscript : MonoBehaviour {

	public GameObject objectToMove;

	void OnGUI()
	{
	  if (GUI.Button(new Rect(10, 10, 150, 100), "Move The Cube"))
	     {

//Option 1 using AddForce.
//objectToMove.rigidbody.AddForce(Vector3.up*10);

//Option 2 using transform.
//objectToMove.rigidbody.velocity = transform.up * 1;

//Option 3, this will move the object to the coordinates you enter in the Vector3 values.
//objectToMove.transform.position = new Vector3(0, +1, 0);

//Option 4, this might be your most ideal one to use.
//objectToMove.transform.Translate(Vector3.up * 2, Space.World); 

	     }
			
	}
}

More info on both methods above can be found on the below links:

Transfrom information: http://docs.unity3d.com/Documentation/ScriptReference30_search.html?q=transform

AddForce information: http://docs.unity3d.com/Documentation/ScriptReference/30_search.html?q=addforce

thank you very much.