OnMouseDown work through UI elements
There are 1 gameobject with onmousedown function and UI Button at my scene . When gameobject goes behind button and i need to click this button, function onmousedown of gameobject working too. How to avoid this unwanted action ? I tried to attach collider to button, but function of gameobject still works.
Answer by OnikurYH · Jan 22, 2016 at 02:00 AM
Hi, You can make a new script to check is the player hovering the UI Elements
For example (C#):
MyUIHoverListener.cs
Assume that the script is put into the Canvas game object
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class MyUIHoverListener : MonoBehaviour
{
public bool isUIOverride { get; private set; }
void Update()
{
// It will turn true if hovering any UI Elements
isUIOverride = EventSystem.current.IsPointerOverGameObject ();
}
}
MyGameObjectOnClick.cs
This script is attach to your game object it will behind the UI Elements
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MyGameObjectOnClick : MonoBehaviour
{
private MyUIHoverListener uiListener;
void Start()
{
uiListener = GameObject.Find ("Canvas").GetComponent<MyUIHoverListener> ();
}
void OnMouseDown ()
{
if (uiListener.isUIOverride)
{
Debug.Log ("Cancelled OnMouseDown! A UI element has override this object!");
}
else
{
Debug.Log ("Object OnMouseDown");
}
}
}
Hope this can help you =)
This answer saved my life, I couldn't understand why when a canvas is raycast blocking a collider, why does it still call On$$anonymous$$ouseOver() event, but this fixes it, so..., cool!
Answer by i2winners · Jan 10, 2021 at 01:20 AM
hey, I have added something extra to your code , for if you open a UI after clicking the object (like a menu) and it clicks true the UI onto other objects that are under a button
`private void OnMouseDown()
{
if (!GameManager.instance.ObjectClickBlocker)
{
if (uiListener.IsUIOverride)
{
Debug.Log("Cancelled OnMouseDown! A UI element has override this object!");
}
else
{
Debug.Log("Object OnMouseDown");
ToggleBuildingMenu();
}
}
}
public void ToggleBuildingMenu()
{
BuildingMenu.SetActive(!BuildingMenu.activeSelf);
GameManager.instance.ObjectClickBlocker = BuildingMenu.activeSelf; // sets same as menu, so if menu active blocker is active
}`
and n the GameManager add a public bool
Answer by d2clon · Feb 24, 2021 at 05:05 PM
This is the only thing that worked for me:
if(!EventSystem.current.IsPointerOverGameObject())
{
// my code
}
Jason explains it here: https://www.youtube.com/watch?v=rATAnkClkWU&ab_channel=JasonWeimann
Your answer
Follow this Question
Related Questions
Share button AR 0 Answers
WEIRD EVENT SYSTEM BUTTON SELECTION 0 Answers
Move gameObject on UI Button Press 2 Answers
I can't use any UI elements in my Project 0 Answers
canvas child of another canvas issue 0 Answers