Using RayCast to see if button clicked
I get the button using this:
Button button = GameObject.FindGameObjectWithTag("MainCanvas").GetComponentInChildren<Button>();
And then I do:
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, hit))
{
if (button.collider.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), hit))
{ //Code to run when button clicked
}
}
}
However I keep getting errors on this. Any idea where i've gone wrong? Thanks
Argument 1: Cannot convert from UnityEngine.Ray to UnityEngine.Vector3 Argument 1: Cannot convert from UnityEngine.RaycastHit to UnityEngine.Vector3
Component.collider is obsolete. Property: collider has been depricated
Component does not contain a definition for Raycast and no extension method 'Raycast' accepting a first argument type of 'Component' could be found
Answer by OctoMan · Oct 08, 2015 at 01:23 PM
Normally you do:
if(Physics.Raycast(ray,out hit,rayLength))
{
if(hit.collider.tag == "button")
{
//do what ever
}
}
If you tag the button , you dont need to get the component from somewhere, basicly. Or you try:
if(Physics.Raycast(ray,out hit,rayLength))
{
if(hit.collider.gameObject == button)
{
//do what ever
}
}
Maybe it helps. Cheers
Edit: Don't forget to add a collider to your button ;)
Doesn't this just see if the mouse is hovering over the object though, and not if it's been clicked?
Where i wrote
//do what ever
you just make the test like :
if(Input.Get$$anonymous$$ouseButtonDown(0))
{
Debug.log("Oh no! The mouse button was clicked on that button!")
}
rayLenght is a float of the length the ray can be, maybe
private float rayLength = 10f;
If you don't know the length of the ray you need, you can say:
private float rayLength = $$anonymous$$athf.infinity;
Cheers and good luck
Seems no message is returned when click button. Thanks will keep trying
It's the left mousebutton. I wonder what you want to achieve anyways. The new canvas system automaticly support OnClick events on Buttons, even Touch Input.
Why you need a raycast for this?
Oh and if it's not responding it can be thats there is another collider infront of it! Debug the hit what you actually hit!
Your answer
![](https://koobas.hobune.stream/wayback/20220612040516im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Spawn added objects into a circle 1 Answer
how to do on single click fire and on drag appears the joystick and get the input from joystick 0 Answers
Movement Unit (RTS) 0 Answers
Car from Unity's standard assets giving me of null reference errors 0 Answers
How do I resolve, get_isActiveAndEnabled can only be called from the main thread error 1 Answer