Select something using mouseclick

Hello everyone,

I’m quite new with Unity and am starting to build a tower defense.

I’ve set up a few things but now I wonder how I might select something.

I need, during the game, to be able to select something and make it do something (ex: select a tower and make it aim at a certain place). But i’ve yet to figure out what to do and how to do it. I fugure I’d need to use MonoBehaviour (already using this), but that’s as far as I got.

Anyone can give me any info on that? Thanks!

The OnMouseDown event call of the MonoBehaviour class is your friend :wink:

Simply attach a collider and a script to your tower object and implement the OnMouseDown function.

I would use the onMouseDown method to handle the mouse clicks for the object. Make a script that has a method void OnMouseDown() and then do the selection from the object script.
Your object must have a collider on it however for this to work.

so:

void OnMouseDown()
{
//script this is in, is attached to the object you want to be selectable

//add object this script is attached to your list of selected objects
//instantiate a prefab that displays the object is selected.

}

I would use a selection manager singleton to do this however. I have my singleton just do a single raycast using a mouse click to hit an object with a collider, check if i can select it, instantiate the prefab, and add it to its list of selected objects.

I also take into account if this item is already selected by checking for the prefab (by name) as a child of the root gameobject of the unit, and deselecting it.

This seems to work just fine for me, as you won’t be selecting more than one object at a time with this, so a raycast is fine.

Hope i’ve helped.