- Home /
Raycast problems
Hello. I'm very new to unity, and I'm making a platformer for a bit of practice. I've run into a bit of a problem with my raycast I'm using for ground and enemy detection. When the player is over a space with no ground below it, I receive this error message:
"NullReferenceException: object reference not set to an instance of an object. PlayerMovementProto.PlayerRaycast () (at Assets/Scripts/PlayerMovementProto.cs:57)"
I'm certain this has to do with the Raycast not hitting anything, but how do I fix it other than always having something below the game's pits?
Here's my code:
Answer by SlowCircuit · Jun 18, 2018 at 02:02 AM
When a raycast hit's nothing, it returns null. In your case, when there is no ground, it hits nothing and sets 'hit' to null. Then when you use hit in any way, it throws an error because you can not get the distance or collider from something that doesn't exist.
Easy Solution:
if (hit == null) {
// Do anything you want to do when there is nothing there
return;
}
Put that after right after you do the raycast, before you check if it's ground or anything else.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
raycast destroying player? 2 Answers
Raycast only works while moving 2 Answers