Mouse click, colliders for items selection vs buttons clicks

Hi guys,

my current problem in a few words :

To select towers in my game you click on them, to deselect them you just have to click on another tower or just anywhere else. So far it worked, now i got made the towers a GUI for upgrades and stuff.

Problem is, that obviously the click on the buttons seen as a click “anywhere else” and so the tower gets deselected.

The way i used to get the tower click was the standard one (this is a supersimplified version just to show how i did it).

[

if(Input.GetMouseButtonDown(0)){
            RaycastHit2D hitP = Physics2D.Raycast(new Vector2(mainCamera.ScreenToWorldPoint(Input.mousePosition).x, mainCamera.ScreenToWorldPoint(Input.mousePosition).y),Vector2.zero,0.0f);
            if(hitP.collider!=null){
...
}else{
 //deselect
}
}

I tried to put a boolean guard on the button click, (so if the button is being clicked don’t deselect) but the click of the raycast is taken before the button click, so it doesn’t work.

Is there any smart “known” way to do this without having to completely change the whole selection approach i used?

Best,
Cheers
H

Ok, through babystep i got to the point that adding a collider to the buttons helps in this. Is it the only reasonable way? (it is only a bit a annoying for non standard shaped buttons as i can’t get the polygon collider out of the image as i do for the sprites)

Cheers,
H

Another way is to add a Physics raycaster to your towers, what this will do is make them work with the event system. They will then be eligible for event system events like ‘pointer down’ and similar.

Ah ok, I didn’t know about that, thanks! How performant is it compared to raycasting the way i was doing it?

It uses raycasts under the hood, it just unifies the UI and physics / ingame stuff.

1 Like

Hi Tim, I am using your method, and despite an initial success i have some very very weird problems shown here :

How does the default Physics2D Raycaster behavior differ from the manual one i used before?

RaycastHit2D hitP = Physics2D.Raycast(new Vector2(mainCamera.ScreenToWorldPoint(Input.mousePosition).x, mainCamera.ScreenToWorldPoint(Input.mousePosition).y),Vector2.zero,0.0f);

The old one was working, the new ones has those very strange effect only on some areas of the viewport and only on some zoom levels of the camera. I am going nuts, since hours, having no clue anymore on what i could try to set and change.

Cheers
H