- Home /
(2D) Raycast check - null reference even when (RayHit != null)
Why is there a null reference if I check if it is not null? Are there any solutions? (The error returns when the player is runnig away from the enemy, not all the time)
var rayHit : RaycastHit2D = Physics2D.Raycast(transform.position , target.position-transform.position,1000,LM1);
if(rayHit != null){
if(rayHit.transform.tag == "Player" && distance < chaseDistance && Vector3.Angle((target.position-transform.position),transform.right)<sightAngle){
//do something
}
thanks in advice
Answer by CHPedersen · Sep 26, 2014 at 08:25 AM
You correctly tested rayHit versus null, but there are more references in there which could be null. Remember, a NullReferenceException happens any time you attempt to access anything on an object, the reference to which is null. An 'access' is every time you write yourObject.something.
In your code: Have you studied the callstack returned by the NullReferenceException? It tells you exactly which line the exception occurs at. What if it's before the if-sentence that checks rayHit? If you haven't set your target in the editor, then target is null and "target.position" raises the exception, too.
Answer by 767_2 · Sep 26, 2014 at 08:35 AM
RaycastHit2D is a struct so you cant use null reference use this instead
if(rayHit != null && rayHit.transform != null)
Your answer
Follow this Question
Related Questions
raycast shooting 0 Answers
Ignore NullReferenceException error? 2 Answers
Error with Update and OntrrigerEnter funtion 1 Answer
Raycasting in script suddenly stopped working 1 Answer
Object reference not set to an instance of an object help (JS) 0 Answers