(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

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.

RaycastHit2D is a struct so you cant use null reference use this instead

if(rayHit != null && rayHit.transform != null)