Unity raycast don't work

Hello, I’ve a 2D world with camera at z=-20, canva and some gameobjects. I’m trying to get the GameObject I did hit and the position of the hit, but it’s not working, I always get coord 0 0 and it says I hit no target, can someone help ? Thanks in advance

if (Input.touchCount > 0)
{
            Touch getTouch = Input.GetTouch(0);


            if (getTouch.phase == TouchPhase.Began)
            {

                Ray ray = Camera.main.ScreenPointToRay(getTouch.position);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
                {
                    if (hit.collider.gameObject == this.gameObject)
                    {
                        selected = true;
                        this.transform.localPosition = hit.point;
                        Debug.Log(hit.point);
                    }
                }
            }
}

Don’t just print the point, print the name of the collider in there.

Strip everything out, make only a few objects in the scene (the bare minimum to prove the script) and figure out what is happening by debugging.

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

In fact it worked when my GameObject where in the canvas, but it’s not convenient. The Debug.Log(hit.collider.gameObject); do not even show anything and when I debug.draw the raycast there is nothing. If you have any code I can find on the internet to get some inspiration, I take

OK so your camera is at 0,0,-20?
How did you form your layermask?

You mention it says no hit target your code has nothing that does that.

Id suggest debugging

a) getTouchposition
b) layermask
c) if/what it hits not just if its you
d) is this on a ton of objects? that would be very inefficient.

That’s not how any of this works. You still have to debug code to make it work.

Good luck.


Send me a script / the scripts please!

You said this was a 2D “world” but you’re using 3D physics here.

If this is 2D then you’d use Physics2D.OverlapPoint().

If you’re using 3D physics then please don’t tag this as 2D. The 2D tag is for when it relates to 2D features. UI/UGUI is not a 2D feature.

Thanks.

1 Like