"Click away" for non-canvas ui?

I’m making a tower defense game, and for my tower placement objects I have an OnMouseUp method that spawns a “button”. I say “button” in quotation marks because it’s just a sprite with a collider. I did it this way so that I can position it near the tower placement objects in the scene, instead of on the canvas.

I also have a script on another object that, in the Update function, detects MouseButtonDown anywhere on the screen (if a “button” exists) and closes the “button”, allowing me to click away from the UI… but applying this script means I can’t click on the “button”!

The behaviour I want is that clicking on the tower placement object spawns the “button”, and while the “button” is active, clicking on it builds a tower, and clicking anywhere else on the screen deactivates it. Does anyone have a suggestion for how I might accomplish this?

Hi @GigaHand. The way you’re doing it needs lots of work. There is already a cleaner solution to it with the UGUI and using canvas. You just need to set your canvas to be in the world space. Creating a World Space UI - 2019.3 - Unity Learn


Finally after that’s done you can do something like this:

  1. Create a prefab containing the canvas (world space) with a button.
  2. Instantiate that prefab in the place you want.
  3. Then do something to manage the last clicked object with EventSystem.current.currentSelectedGameObject; and control with your button whether or not it was that button clicked, if it wasn’t the active button, then you should disable that button or invalidate it the way you want

Here is a simple example I wrote for you: https://github.com/AbreuRodrigo/global-click-management

Thank you very much for your help, I’ve made progress thanks to your advice and your link. I have shifted the “button” to an actual Unity UI button on a world space canvas, but for the rest of your advice I shall look up Unity’s event system, I’m still somewhat new to this but if it’s the recommended way to handle this sort of thing then it must be quite useful in general.