- Home /
Clicking on objects
I am making a TD game and I need to be able to upgrade my turrets. Unfortunately I do not have the knowledge to do such a thing. Do note that I am NOT using a grid system. Any help is appropriated in advance. Thanks!
Answer by Statement · Dec 19, 2012 at 01:02 AM
There's OnMouseDown, or you can do a ray cast when you click the mouse button to do stuff with the object that the raycast hit. Both solutions require a collider on the object. These are two ways of doing it that I think are pretty easy and popular.
OnMouseDown (easy):
http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnMouseDown.html
Raycasting on click (pretty easy, requires more code, gives finer control):
http://docs.unity3d.com/Documentation/ScriptReference/Input.GetMouseButtonDown.html http://docs.unity3d.com/Documentation/ScriptReference/Input-mousePosition.html http://docs.unity3d.com/Documentation/ScriptReference/Camera.ScreenPointToRay.html http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
Answer by aldonaletto · Dec 19, 2012 at 01:10 AM
Do you want to know how to click an object and replace it with another one? If so, use OnMouseDown in the object script:
var nextObject: GameObject; // drag the replacement prefab here
function OnMouseDown(){
// create the new object at the same position and rotation
Instantiate(nextObject, transform.position, transform.rotation);
// destroy the older one
Destroy(gameObject);
}
I want to just be able to select the object. Not replace it with anything. Also I only want to be able to select one object at a time.
If you want to select one object at a time, use Raycast as @Statement said - for instance (script attached to the camera):
var selected: Transform;
function Update(){
if (Input.Get$$anonymous$$ouseButtonDown(0)){ // if left button pressed...
// create a ray passing through the mouse pointer:
var ray = camera.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)){ // if something hit...
// if you must do something with the previously
// selected item, do it here,
// then select the new one:
selected = hit.transform;
// do whatever you want with the newly selected
// object
}
}
}
Currently what happens is that whatever I hover over is selected, but not when I click. How would I achieve this? O am not an expert in this field of scripting. Thanks!
$$anonymous$$aybe you're using my first version - I forgot to include the mouse button reading, which I fixed a few $$anonymous$$utes after. Take a look at the current code: it includes an enclosing if which only does the Raycast when the mouse button is pressed.
Great! That works! And I can use GetComponent to make things happen right?