I'm trying to detect touch on selected gameobject using RaycastHit2D. The game is 2D. Below is my code :
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
Debug.Log("touch");
Vector3 touchPosWorld = Camera.main.ScreenToViewportPoint(Input.GetTouch(0).position);
Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);
RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);
Debug.Log(hitInformation.collider);
}
}
I have attached that script to empty gameobject. Then create a prefab with a box collider in it. But when I touch the prefab with boxcollider2d on it still says Null. What's wrong with my code