Selecting and moving an individual object during gameplay..

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);

}

Thanks!

Hey there, I’m somewhat of a beginner myself, but I think I can help. A simple way to this would be to use OnMouseUp: http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnMouseUp.html

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!

THANK YOU SO MUCH!!!

That’s brilliant mate, works perfectly.

Thanks again.