- Home /
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!
Answer by Tommynator · Feb 27, 2012 at 02:18 AM
The OnMouseDown event call of the MonoBehaviour class is your friend ;)
Simply attach a collider and a script to your tower object and implement the OnMouseDown function.
Thanks, I've just read a few things following your suggestion. Problem is, now, that I can't fathom how to use it. Any ideas?
Answer by 1337GameDev · Aug 26, 2013 at 02:41 AM
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.