- Home /
Create UI raycast like a mouse Click
Hi! I have a button which is located on Canvas and i need to simulate user click on it, not using Button component and onClick method, but just using raycast. Click event programmaticaly like a mouse left button click. Have any ideas how can i realize it?
Answer by badadam · Jan 14, 2019 at 08:38 AM
The parent canvas of your button has Canvas component.. This component's render mode must be "Screen Space - Camera". And add the main camera to Render Camera
Add Box Collider to your button. Use edit collider button and change size and center values to cover your button with box collider.
And add the script below to your button as a component
public class ButtonClick : MonoBehaviour {
public Camera mainKamera;
private RaycastHit raycastHit;
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
Ray ray = mainKamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray,out raycastHit))
{
if (raycastHit.collider.gameObject.name=="myButton")//this string must be name of your button I named my button myButton
{
Debug.Log("clicked");
}
}
}
}
}
Answer by himanshugupta159 · Jan 14, 2019 at 06:54 AM
Written a blog related to the question link is added below. https://unfragilecoding.blogspot.com/2019/01/how-to-make-all-gui-components.html
Your answer
Follow this Question
Related Questions
Raycast against UI in world space 4 Answers
Unity 5 new UI Button Colliders moved to the left in different resolutions 1 Answer
How to make UI block clicks from triggering things behind it 7 Answers
Can't get results from GraphicRaycaster.Raycast 0 Answers
Display issues with GUI only showing details for last object in list. 2 Answers