- Home /
Click anywhere to deselect active GameObject
I am building a ObjectSelector
script that every selectable GameObject will use. The class communicates with the class ClickHandler
which stores the current selected GameObject
.
What is the best approach to register clicks that are not on any of the selectable GameObjects? If the player clicks anywhere in the game I would like the ClickHandler
to deselect the active GameObject.
Answer by save · Oct 17, 2011 at 10:26 AM
You could deselect it first then if a physics.raycast hits an object that is selectable you select it. To determine if the object is selectable you could have a script (which could be empty) attached.
if (Input.GetButtonDown("Fire1")) {
ClickHandler.SelectedObject = null;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
if (hit.transform.GetComponent(selectable)) {
ClickHandler.SelectedObject = hit.transform;
}
}
}
The code is not tested but should give you an idea of what to do.
Answer by mnml_ · Oct 05, 2017 at 02:19 PM
I solved this without a 'catch-all-collider':
https://docs.unity3d.com/Manual/ExecutionOrder.html states that input events are always processed before any update/coroutines. so I have a behaviour containing OnMouseDown and OnMouseUp handlers on my gameobjects with colliders which detect clicks, and one (singletonized) behaviour doing the same 'click-detection-logic' in a coroutine (watching Input.GetMouseButtonDown and Input.GetMouseButtonUp) when a gameobject with collider detects getting clicked it sets a bool-flag on the singleton (bool clickSourceKnown) true. when the singleton detects a click and clickSourceKnown is false it was a 'click in the air' - otherwise it resets the clickSourceKnown to false and continues watching the Input...
This is brilliant! A super simple solution, yet powerful.
Answer by swisscoder · Oct 17, 2011 at 06:56 AM
you can draw a big big collider around your scene, where you catch the OnClick too. So you can deselect the last GameObject from the ObjectSelector when you click "anywhere" (anywhere=>click on the big collider around your scene)
I was hoping to avoid the "big collider" idea. Looking for a general click ins$$anonymous$$d of relying on a GameObject.
you could catch the $$anonymous$$ouseButtonDown in a "global" like method, but then you wouldn't know if it was while clicking a GameObject or not. But with script execution order you could probably check before and after the marked GameObject if a new one was clicked..
Your answer
Follow this Question
Related Questions
Move selected object. 1 Answer
How to NOT select an object behind a GUI? 1 Answer
Box Selecting Top-Level Transforms Only 0 Answers
How to select a hidden MeshRenderer in SceneView? 0 Answers
How to multi-select scene hierarchy objects in code 0 Answers