- Home /
Detect mouse clicks anywhere on the screen except given gameobject
I have two gameobjects with scripts attached to them. In first script, I've implemented OnMouseDown() so the script reacts when user is clicking that object. And I want second object to react when i'm clicking elsewhere on the screen. I've tried Input.GetMouseButtonDown() but that doesn't seem to work, because in this case second script runs even if i click first object.
Answer by ByteSheep · Jan 14, 2012 at 07:03 PM
You could use a boolean that is set to true or false depending on whether the mouse is on the object. Something like:
var MouseOnObject : boolean = false;
function OnMouseEnter() {
MouseOnObject = true;
}
function OnMouseExit() {
MouseOnObject = false;
}
function Update () {
if(Input.GetButtonDown("Fire1") && !MouseOnObject)
{
//clicked elsewhere on screen
}
}
This should work but give it a try and let me know :)
hi nice solution! but what can i do when the issue is smartphone.. On$$anonymous$$ouseEnter wil not help in this situation..
on mobile you can use ray casting to see whether clicked on the object or elsewhere.
Answer by ivan1992vuja · Oct 03, 2018 at 10:46 AM
this post is quite old but, but still useful i changed the code a bit and for C# it works like a charm
using UnityEngine.EventSystems;
public class DisableGameObjectClickedOut : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
bool MouseOnObject = false;
public void OnPointerEnter(PointerEventData pointerEventData)
{
MouseOnObject = true;
}
public void OnPointerExit(PointerEventData pointerEventData)
{
MouseOnObject = false;
}
void Update()
{
if ((Input.GetMouseButtonDown(0)) && (!MouseOnObject))
{
this.gameObject.SetActive(false);
}
}
}
Your answer
Follow this Question
Related Questions
Disable mouse input and cursor in game 2 Answers
Unity Web Player does not respond to mouse clicks 1 Answer
Mouse click is detected twice 1 Answer