Search Unity

Question Canvas group, images and buttons don't block raycast, seem to be ignored entirely

Discussion in 'UGUI & TextMesh Pro' started by dasyel, Feb 17, 2021.

  1. dasyel

    dasyel

    Joined:
    Nov 2, 2016
    Posts:
    2
    Hey everyone, I've been stuck on this problem for a few days now.

    The context:
    I'm making a diablo like game, so it's click to walk. I use a physics raycast to see where I clicked in the world and walk there. This works fine. Now I've created a screen space overlay canvas for an inventory screen that only fills part of the view. The inventory system consists of some layered images and buttons for the inventory slots.

    The problem:
    whenever I try to click on the inventory window, my character just walks over to the area behind the window. The inventory window doesn't block the raycast.

    What I've tried:
    - Made sure there's an event system in my scene
    - Made the background image of my window a raycast target.
    - Added a canvas group with "block raycasts", "interactable" and "Ignore Parent Groups" (I've tried every combination of these settings)
    - Set the sort order of the canvas way up so it's defnitely the first thing on my screen.
    - Added a transparent non-interactable button the size of my inventory window on my canvas
    - Tried the following piece of code
    Code (CSharp):
    1.  if (Input.GetMouseButtonDown(0) && EventSystem.current.IsPointerOverGameObject()) {
    2.       print(EventSystem.current.currentSelectedGameObject.name);
    3. }
    It doesn't matter whether I click on my inventory window or somewhere in the game world, this always triggers and always causes the following error
    NullReferenceException: Object reference not set to an instance of an object

    - I've selected the event system in my scene while mousing over different objects and it does show the correct objects there ("Image", "Terrain")

    I think I've tried everything I could find through google and youtube, but nothing works. I'm totally fine with programmatically blocking the raycast, as long as there is some way for me to know that the UI was clicked.

    I really hope someone can help me, I'm at my wits end.
     
  2. dasyel

    dasyel

    Joined:
    Nov 2, 2016
    Posts:
    2
    Found a way around it for now. I implemented the IPointerEnterHandler and IPointerExitHandler on my inventory script. And I created a delegate to send an event to my player controller which can now stop raycasting if the mouse is over the inventory window. I haven't tested yet if the handlers also trigger when I open the inventory window with my mouse already over that same area. Hope that will work.

    If anyone has the feeling I can do this in a better way, please let me know.