- Home /
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?
Answer by robertbu · Oct 06, 2014 at 08:27 PM
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.
Yes, I will create error reporting later, but my terrain locate at (-250, 0, -250)
Well if you are getting a null reference exception, you need to put your error reporting in now. You could put this in the 'else'
Debug.DrawRay(ray.origin, ray.direction, Color.red, 10.0f);
Then you could look at the raycast that failed to see what is going on.
it is not about error reporting, it is about error handling. You should start by architecturing your code as requested above to better comprehend what happens.
Your answer
Follow this Question
Related Questions
Creating a working meshcollider in code 3 Answers
Raycast isnt working 1 Answer
Flattening terrain under my object at start() 1 Answer
why are child colliders sometimes ignored? 2 Answers
Someone can help with Ray/Collide? 1 Answer