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.
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
{
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 =)
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
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