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)
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.