- Home /
detect click on canvas
Hello
I'm trying to add a HUD in my project and I want that when I click on the canvas ( which is 20% of the screen ) my player dont move.
It's moving by a raycast statement, so I tryied this but it doesnt work :
if (Physics.Raycast(ray, out hit) ) {
if(hit.transform.gameObject.layer == 5)
{
print("Ui element was click");
}
SetDestination();
}
Answer by TreyH · Jul 08, 2018 at 01:32 AM
There's a fairly detailed example in the docs to do just this. I'll clean their example up a bit for you, but the modifications for your exact situation are straightforward.
As mentioned on that page, this will be attached to your Canvas object so that it can access its GraphicRaycaster
component.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class CheckClicks : MonoBehaviour
{
// Normal raycasts do not work on UI elements, they require a special kind
GraphicRaycaster raycaster;
void Awake()
{
// Get both of the components we need to do this
this.raycaster = GetComponent<GraphicRaycaster>();
}
void Update()
{
//Check if the left Mouse button is clicked
if (Input.GetKeyDown(KeyCode.Mouse0))
{
//Set up the new Pointer Event
PointerEventData pointerData = new PointerEventData(EventSystem.current);
List<RaycastResult> results = new List<RaycastResult>();
//Raycast using the Graphics Raycaster and mouse click position
pointerData.position = Input.mousePosition;
this.raycaster.Raycast(pointerData, results);
//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
foreach (RaycastResult result in results)
{
Debug.Log("Hit " + result.gameObject.name);
}
}
}
}
Thanks !
I ill look at this
But as far as I understand, it's on the canvas that i must put this script, so, I have no idea to go forward with my issue which is on my player script
$$anonymous$$y player have a script attached to and on this script I said when I click somewhere, move to this point
I would like to make this function unavailable if the click is on the canvas so my player dont move
Have you any idea ?
Edit : Ok I see why it's not working on my 1st post , do you suggest me a static var to communicate between script to know if the click was on the canvas ?
This doesn't necessarily have to be on your canvas. This just has to reference the components on your canvas. There are several ways to go about this, but those are all covered extensively across this forum.
O$$anonymous$$G this finally works!!! Thank you so much!!! <3
Thanks a lot, I finally find your solution possible for me :)
Your answer
Follow this Question
Related Questions
Get name of UI element by RayCasting 1 Answer
Two cameras depth-sorting correctly (for use with blur etc.) 0 Answers
[4.6 GUI] Displaying my pause menu when ESC is pressed 2 Answers
Canvas & Player spawning 1 Answer
rendering panel w/children 0 Answers