using UnityEngine;
public class clickOnObject : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
senseObject();
}
void senseObject()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
if (hit.collider != null)
Debug.Log("Hit! " + hit.transform.name);
}
Debug.DrawRay(Camera.main.ScreenPointToRay(Input.mousePosition).origin, Camera.main.ScreenPointToRay(Input.mousePosition).direction, Color.blue);
}
}
If it’s 2D physics then use OverlapPoint after you’ve calculated the point in world-space, a Ray doesn’t really make sense. That said, there’s GetRayIntersection that allows you to specify a ray and it’ll perform all the 2D projection to give you a pseudo 3D raycast results.
Collider2D col = Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition));
if (col != null)
{
//Do something...
}
Both are working great and both use same lines of code, so which one should I use, OverlapPoint I guess…?
Is there anything else I can do to make it more efficient?
I’m not sure the Raycast one is correct. Raycast performs its work in XY and not Z so if you’re trying to raycast along Z then you need to use OverlapPoint or GetRaycastIntersection. OverlapPoint is much faster/efficient however.
In your case using Raycast, the direction doesn’t matter. You’re probably only picking up colliders where the ray begins anyway so it’s sort of an odd case.