- Home /
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!
Answer by Story Specialist · Oct 13, 2011 at 04:45 PM
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!
THAN$$anonymous$$ YOU SO $$anonymous$$UCH!!!!!
That's brilliant mate, works perfectly.
Thanks again.
@jw120691: $$anonymous$$y pleasure! I'm glad it worked. Can you please Accept my Answer, so others know a solution has been found? :)
Your answer
Follow this Question
Related Questions
Selecting and moving an individual object during gameplay.. 2 Answers
How to drag and drop a instantiate prefab on my mobile game 3D using touchs! 0 Answers
Make an object move to a given point by rotating to the correct direction first. 1 Answer
Object moving sideways when translating using forward vector. 1 Answer
how do i slowly translate a object to a other objects position 2 Answers