- Home /
Raycast function doesn't work.
GameObject GetObject(Vector2 pos)
{
Ray ray = Camera.main.ScreenPointToRay(pos);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
return hit.transform.gameObject;
}
return null;
}
I never had problems with raycasting before. This simple method always returns null even though there's always an object at given Vector2 position. I have colliders attached to my objects, in fact I'm using raycasting in other scripts and they work just fine. So what could be the problem?
Edit : Well, I ended up using OverlapSphere instead but that used almost a quarter of my cpu since I had to call it every frame. So I'm back to simple raycast. Here's more further info
Ray ray = new Ray(new Vector3(1,2,0), Vector3.zero);
print(ray.ToString());
What I get :
Origin : (243.4, 104, 0)...
How's that even possible?
Answer by wibble82 · Mar 11, 2014 at 05:39 PM
Nothing obviously wrong with that code. Have you tried Debug.Log to print out the input pos, and ray information. Might point to some dodgy data. You can also use the debug rendering to draw the actual ray in the edit view, so you can confirm visually that it is intersecting the collider of a target object.
Also worth checking whether the colliders are set to 'trigger' - I'm not sure whether rays detect trigger intersections by default.
I tried them all. Everything seems fine and in place. It just doesn't pick up the object.
The object has a collider and is not on the ignoreRaycast layer? Is the collider a mesh collider or a simple one?
And you're sure pos is right? Debug.Logged it? It's in pixels?