Home > Back-end >  IPointerClickHandler doesn't work on unity game object
IPointerClickHandler doesn't work on unity game object

Time:12-20

I have unity 2D project and I wanted to detect left click event on the player game object.

  1. I added Physics2DRaycaster to MainCamera (see the first screen below)

  2. I added two colliders to the game object (the circle collider is for detecting collisions, the box collider is triggered and used for click detection through IPointer) (see the second screen below)

  3. I implemented the interfaces: IPointerClickHandler, IPointerEnterHandler, IPointerDownHandler in the game object script. (see the code below)

  4. I have EventSystem object in scene (see the third and fourth screen below)

  5. I checked with a simple project that this combination works

But still in my project any click event isn't detecting at all. I have not idea why. I think the raycast itself doesn't work, because when I look at EventSystem logs in inspector I see that the player object doesn't detected.

UPDATE: I saw that if I switch off the canvas the IPointer gets work. But canvas elements is placed only around the player gameObject (menu buttton), but the game object isn't hided by the canvas

UPDATE 2: Ok, I figured out that even if the canvas panel is transparent it still hides the game objects. So my question is, how can I detect click on game object if the canvas pannel is in front of the game object?

This is the script of the game object:

public class Player : MovingCharacter, IPointerClickHandler, IPointerEnterHandler, IPointerDownHandler
{

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("Down");
    }
    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("Clicked");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Entered");
    }

    //other code......
}

This is the MainCamera:

enter image description here

This is my Game Object (Player):

enter image description here

This is the EventSystem:

enter image description here

And this is the project structure:

enter image description here

CodePudding user response:

Use layers!

If you want to be able to hit the object then put your menu on a special layer like e.g. UI and make sure the PhysicsRaycaster2D ignores that layer.

UI will be Interactable anyway since the Canvas's own raycaster already takes care of UI elements.

In general I would also make sure to only mark these elements as Raycast Target that are actually Interactable (e.g. buttons). This way an invisible background panel wouldn't block the input either.

  • Related