- Home /
How Do You Select A Game Object By Using the Left Mouse Button?
Hey everyone I am trying to make a game but one of the main parts to it is selecting game objects with the left mouse button. I was wondering if anyone knew the java script to allow you to click on a game object and the game object change color or something as a result. Also just to mention I have very little experience with this and have done little to no coding/scripting or whatever it is called. I have checked google and the results I have found have been of little help due to my inexperience. Also does anyone know how to make this work for prefab or instantiated objects too? Any help is appreciated.
I dont use javascript. But a good tip is to try raycasting. You could easily get the gameobject by doing so. :)
Answer by DaveA · May 11, 2013 at 08:45 PM
https://www.google.com/search?q=Select+A+Game+Object+By+Using+the+Left+Mouse+Button
Does anybody read the docs? http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit-collider.html
Im certain it is but im new to this and have practically no idea what most of it means, but thank you for the help none the less.
Answer by aldonaletto · May 11, 2013 at 09:01 PM
A common method is to use Raycast in a camera script, and change the hit object properties - like this:
var hitTransform: Transform; // transform of currently selected object
function Update(){
if (Input.GetMouseButtonDown(0)){ // if left mouse pressed...
// create ray passing through the mouse pointer:
var ray = camera.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)){ // if something was hit...
hitTransform = hit.transform; // get a reference to its transform
//
// and do whatever you want with this object here
//
}
}
}
The variable hitTransform holds the transform of the last object clicked.
Okay thank you so much this is exactly what I needed.
I have an issue though because the object I want to select is going to be a prefab and this works fine for selecting a game objects but how can I select prefabs individually in this method?
Well, prefab selection is editor script stuff: you must save your script in Assets/Editor and use the Editor classes - there's a Selection class that lists all selected objects. I played too little with Editor scripts, but suppose that you don't have to worry about the selection code - just inspect the Selection class to know which objects are selected.
Your answer
![](https://koobas.hobune.stream/wayback/20220613102033im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to tell if 2 blocks are next to each other in a 2d game? 1 Answer
Hit any gameobject, animation will play? 1 Answer
What variables can i declare? 1 Answer
Destroy GameObject A or B 1 Answer