- Home /
How to make an object go upward when button is click
This code is working well, but only one o object is moving upward when i click the button. How can i make that when i tap the button multiple objects will move upward?
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);
}
}
}
Answer by ragnaros100 · Jan 21, 2014 at 12:16 PM
you can create an array of GameObjects that you'd like to move. Afterwards you can make a for loop (or a foreach loop) in order to move them all simultaniously:
public GameObject[] objectsToMove;
void OnGUI()
{
if(GUI.Button(new Rect(10, 10, 150, 100), "Move The Cubes")
{
foreach(GameObject object in objectsToMove)
{
//Move object here using Option1
object.rigidbody.AddForce(Vector3.up*10);
}
}
}