Raycasthit2D.point not working properly on tilemap

Hi I am making a 2d platformer game I am using this code to spawn structres randomly on the map

         for (int j = 0; j < maxPillars; j++)
         {
          hitt = new Vector2(Random.Range(-width / 2, width / 2), 100);
        
        RaycastHit2D hit = Physics2D.Raycast(hitt, -transform.up,Ground);
        print(hit.point);
        if (hit != null)
        {
           
            Instantiate(spawnPillar).transform.position = new Vector2(hit.point.x, hit.point.y + 1) ;
        }}

And I am using a tile map , the raycast point would always be 0,0,0 for some reason

Sounds like you wrote a bug… and that means… time to start debugging!

At a mininum, print what the name of the hit collider is from within the hit structure.

We know raycast didn’t stop working, so your challenge is to find out what you have done wrong.

For two, variables names like hitt when you already have a hit are just going to confuse you, so don’t do that. Name it whatever it is, perhaps position or raycastStart or something.

Also, print out these values that you are feeding into the raycast. Are they reasonable? Use OnDrawGizmos to see them in the game in realtime.

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.

Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.

1 Like