Rays: why is not working?

I have a terrain. It’s size 500x500 with center in (0,0).

I want to create ray, but sometimes I have null reference exception, because my ray not colliding to any objects.

My code:

    				pos = new Vector3(Random.Range(-200f, 200f), 400f, Random.Range(-200f, 200f));
    				Ray ray = new Ray(pos, Vector3.down); 
    
                    Physics.Raycast(ray, out hit, 50000);
    
                    if (hit.collider.name == "Terrain") //sometimes null reference exception
                    {
                        //do actions
                    }

I see what Ray.origin is not same as “pos” vector. It is normal?

I’m unaware of any ‘center’ associated with a terrain. If you are talking about ‘position’, then terrains are achored in the corner. Create a terrain at (0,0,0), then create a sphere at (0,0,0). You will see the sphere in the corner of the terrain. So you will need to either offset the position of your terrain, or offset the ‘center’ position for your ‘pos’ used in the Raycast().

But beyond that, it is bad coding to do a Raycast() and not check the return. Structure your code:

if (Physics.Raycast(ray out hit, 5000)) {
    // Do something
}
else {
    // Report the error
}

Unexpected things happen in code, and you don’t want your app to crash on the device.