RayCast2D CompareTag returning error

I’m trying to cast a ray from my enemy to have it detect my player, to then chase and attack the player while in range of the cast.

Heres my code:

 RaycastHit2D playerDetect = Physics2D.Raycast(detector.position, Vector2.right, playerDetectRay);

        if(playerDetect.collider.gameObject.tag == "Player")
        {
            Debug.Log("Detecting Player");
        }

This, however, is returning an error “NullReferenceException: Object reference not set to an instance of an object” and I’m not exactly sure why

If the raycast doesn’t hit anything, playerdetect.collider would return null! so trying to reach in there won’t work. Try checking if it’s null like this:

RaycastHit2D playerDetect = Physics2D.Raycast(detector.position, Vector2.right, playerDetectRay);
         if (playerDetect.collider != null) 
         {
             if(playerDetect.collider.gameObject.tag == "Player")
             {
                  Debug.Log("Detecting Player");
             }
         }