Hello! I am very new to Unity (currently making my first game) and I am trying to write a script to select and move an individual cuboid object forwards and backwards using the up and down arrow keys. There are 5 cuboid objects in my game and at the moment I have successfully written a script to move them all at the same time but I want to be able to individually move them after selecting them with the mouse during gameplay.
The script I currently have is:
function Update () {
var speed = 5.0;
var move : float = Input.GetAxis("Vertical");
Debug.Log(move);
transform.Translate(Vector3(0, 0, move) * Time.deltaTime * speed);
Make a script and put in an OnMouseUp function. Have this function change a String (eg. SelectedObject). One that you keep in a separate script (I always make a script called GlobalVariables, which holds…global variables ^^). In your original script, make an if-statement that checks if the name of the GameObject it’s attached to, is the same as the SelectedObject. Like so:
function Update () {
var speed = 5.0;
var move : float = Input.GetAxis("Vertical");
if (this.name == GlobalVariables.SelectedObject) {
transform.Translate(Vector3(0, 0, move) * Time.deltaTime * speed);
}
Debug.Log(move);
}
function OnMouseUp () {
GlobalVariables.SelectedObject = this.name;
}
Where “GlobalVariables” is your separate script and “SelectedObject” is the String.
Your GlobalVariables script would be as simple as something like this:
static var SelectedObject : String;
function Update () {
}
Now you can just attach your script to as many GameObjects as you want. I hope that helps you out!