Hello, I have a 2D game I’m building in Unity 2018.2.14f1. I have some panels and buttons in a canvas, and when the user clicks anywhere on screen I want to take the mouse position and find out if they clicked on a child of the canvas or if they clicked on anything else. How can I detect this? Here’s my code in my component that is attached to the main camera game object.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
bool clickedInMenuSystem = //WHAT GOES HERE?
if (clickedInMenuSystem)
return;
// Eventually do something here
}
}
My apologies if I’m posting this in the wrong place or if this has been answered before. I’m new here, and all the answers I found were for the older GUI system.
You want to set up a raycast from the camera to the mouse curser. I think it’s something like ScreenPointToRay().
That should be enough information to get your research started. Sorry, I don’t know more about it.
A bool only reads true or false. So is what you’re doing, seemingly, is determining if something was clicked on a true or false basis. However, you’re only clicking the mouse and firing the left click here. You’re not actually testing any conditions. To do this, you’d need an IF statement. There are ways to test if the mouse curser has collided with an object; however, I think this will lead back to casting a ray and testing the hit. That’s a pretty standard way of gathering information.
you can try with events, the script can be added to canvas (or object).
using UnityEngine;
using UnityEngine.EventSystems;
public class NoIdeaHowToDo : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick (PointerEventData something)
{
if (something.button == PointerEventData.InputButton.Left)
{
Debug.Log("click on " + something.pointerEnter.name);
Debug.Log("position: " + something.position);
}
}
}
or maybe
using UnityEngine;
using UnityEngine.EventSystems;
public class OtherEvent : MonoBehaviour, IPointerDownHandler
{
public void OnPointerDown (PointerEventData something)
{
if (Input.GetMouseButtonDown (0))
{
Debug.Log("click on " + something.pointerEnter.name);
Debug.Log("position: " + something.position);
}
}
}
Thank you all for your suggestions, but what I’m trying to do is some kind of ray trace that includes the children of the canvas. Is there such a thing? All the ray tracing code I’ve tried ignores any children of the canvas.