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?
Written a blog related to the question link is added below.
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");
}
}
}
}
}