Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Mouse Click is passing the GUI

Discussion in 'Immediate Mode GUI (IMGUI)' started by RIw, Jun 11, 2015.

  1. RIw

    RIw

    Joined:
    Jan 2, 2015
    Posts:
    90
    Hi!
    I wrote a simple script which is selecting the GameObject clicked by Mouse:
    Code (CSharp):
    1. public static GameObject SelectedGameObject()
    2.     {
    3.         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    4.         if (Physics.Raycast(ray, out hit, 10f))
    5.         {
    6.             if (hit.transform.gameObject.tag != "Player" && hit.transform.gameObject.tag != "ItemDatabase" && hit.transform.gameObject.tag != "Coller")
    7.             {
    8.                 //return hit.transform.gameObject;
    9.                 if (hit.transform.gameObject != null)
    10.                 {
    11.                     selected = hit.transform.gameObject;
    12.                     QuickMenu.Initialized = false;
    13.                     return selected;  
    14.                 }
    15.                 else
    16.                 {
    17.                     QuickMenu.Initialized = false;
    18.                     return selected;    
    19.                 }
    20.              
    21.             }
    22.             if(hit.transform.gameObject == null)
    23.             {
    24.                 return null;
    25.             }
    26.              
    27.         }
    28.             return null;
    29.     }
    The problem is when I'm clicking on the GUIControls when the GameObject is behind my GUI.My script is selecting the GameObject behind the GUI but I don't want this result.
     
  2. Tamerqarrain

    Tamerqarrain

    Joined:
    Mar 16, 2014
    Posts:
    2
    You can use UnityEngine.EventSystems together with EventSystem.current.IsPointerOverGameObject() and have a bool to decide wither you were on top of a UI element or not like this,

    Code (CSharp):
    1. if (EventSystem.current.IsPointerOverGameObject())
    2.                     {
    3.                         wasOverUI = true;
    4.                     }

    You can couple this with a Canvas Group to decide which UI element is interactable or not.
     
  3. RIw

    RIw

    Joined:
    Jan 2, 2015
    Posts:
    90