Raycast on mouse position problem. how not to raycast to 0
Hi, i try to drop objects from ui into 2d world using raycasting. Object is dropped on the good layer but in a wrong place. Dropped item always shows up on coordinates x=0, y=0, z=0 insted of mouse position in world. i know something is wrong, propbably RaycastHit is not defined but im not sure how to fix this and would apreciate some help
public Camera cam;
public virtual void OnDrop()
{
RaycastHit hit = new RaycastHit();
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 0))
{
gameObject.SetActive(true);
gameObject.transform.position = hit.point;
}
}
Answer by streeetwalker · Jun 10, 2020 at 06:01 PM
You're code should work just fine - I just tested it myself. There must be something else going on. Is gameObject a child of some other gameObject? If you debug hit.point, what value do you see?
Thank you for looking into it! gameObject is not a child, and hit.point value in debuger is 0.0. But there apear to be an error hit.lightmapCoord? It says "NullReferenceException". Its strange cause nothing shows up in console
Wait, when do you generate the error? if you only get it when you try to debug that property of the hit, then I don't think the problem is there, and you can ignore it.
What object is it hitting? Debug that. You are trying to drag something from the UI and move it into 3D space? - I would think that your problem is related to that.
$$anonymous$$aybe your getting a hit on the UI canvas elements, which might explain the UV error.
Perhaps if you tag the object you want to drop on,, do a RayCastAll, and then walk through the returned array and respond only on the tagged items you want to drop your object on.