0
votes

I have a gameobject with collider2d which was designed to be clickable, and I also Have an UI button which will follow the camera while player moving, the thing is they may overlap sometimes, and when they overlap, when user click the overlap area, I am sure that user want to click the object (which was do by raycast2d hit) so I should prevent the button to be clicked.

The script for the raycast implantation of clickable gameobject is as following:

 private void checkTouch()
    {
        if (Input.touchCount > 0 || Input.GetMouseButtonDown(0))
        {
            Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
            RaycastHit2D hit = Physics2D.Raycast(rayPos, Vector2.zero, 0f);
            if (hit)
            {
                Debug.Log(hit.collider.gameObject + "is hit");
                IInputBehavior inputBehavior = hit.collider.gameObject.GetComponent<IInputBehavior>();
                //IInputVehavior was a self-desgined C# interface which has a `OnClick()` method.

                if (inputBehavior != null)
                {
                   //here we should prevent the UIButton to be clicked, but how? 

                    inputBehavior.OnClick();
                }
            }
        }
    }
1

1 Answers

0
votes

Okay so I'm at work so I can't give you the exact code but I can point you in the right direction. When you made the canvas originally it should have generated an event system ( as a game object in the scene somewhere ), you need to reference this in your game object that you want to not click when the ui is over it. In your game object it's something like this:

if(GetComponent<EventSystem>().IsPointerOverGameObject) {
    // The mouse is obscured by a UI element
} else {
    // The mouse is not over a UI element
}

https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html