The question is answered, right answer was accepted
Not Hitting a button with raycast
Good Evening,
I'm developing a game for android. I have several UI buttons and I'm already checking if the button is been touched. The button has a BoxCollider2D, and every time I touch the button it recognize the touch, but the Physics.Raycast is always false. The Script is attached to the Main Camera. Does anyone can help?
using UnityEngine;
using System.Collections;
public class ButtonController : MonoBehaviour {
private GameObject objectHit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
Ray buttonRay = Camera.main.ScreenPointToRay(Input.touches[0].position);
RaycastHit buttonHit;
if (Physics.Raycast(buttonRay,out buttonHit)){
objectHit = buttonHit.transform.gameObject;
objectHit.SendMessage("OnClick",SendMessageOptions.DontRequireReceiver);
}
}
}
}
I believe that there is a problem with the position because of the Rect Transform Position of the button and the position of the touch.
Answer by usalalas · Dec 17, 2015 at 08:08 PM
If found an answer. This script is attached to the main camera.
RaycastHit2D buttonHit;
buttonHit = Physics2D.Raycast(this.transform.position, Input.touches[0].position);
if (buttonHit)
{
objectHit = buttonHit.transform.gameObject;
objectHit.SendMessage("LoadScene",1,SendMessageOptions.DontRequireReceiver);
}
Answer by Susajin · Dec 15, 2015 at 11:05 AM
Are you using a canvas? Make sure that the Raycast Target option in Image Component of the Button is checked. But why are you using Raycasting for button clicks? You can just use the OnClick() Listener in the Button Component to call methods you want.
Good $$anonymous$$orning @Susajin,
The OnClick method is not been called when I touch the screen over the button. The script recognize the touch but doesn't know witch object was touched.