Object Reference Not Set To An Instance Of An Object

Hey y’all. I have this short piece of code written:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyOneManager : MonoBehaviour
{
    [SerializeField] GameObject player;
    int layerMask;

    void Start()
    {
        layerMask = LayerMask.GetMask("Player");
    }
    void FixedUpdate()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, -this.transform.up, 15, layerMask);
        if(hit.collider.gameObject == player)
        {
            Debug.DrawLine(this.transform.position, hit.point, Color.red);
            Debug.Log(hit.collider.name);
        }
        else
        {
            Debug.Log("Not Hit");
        }
    }
}

I’ve added my player game object into the inspector and the raycast works as intended, but I’m getting this error every time FixedUpdate() gets called:

NullReferenceException: Object reference not set to an instance of an object
EnemyOneManager.FixedUpdate () (at Assets/Scripts/EnemyOneManager.cs:17)

Line 17 is:

 if(hit.collider.gameObject == player)

So I’m guessing that Unity thinks that the player game object is not assigned (though it definitely is). Any ideas on how to fix this error? As I mentioned earlier, the script is functioning as intended. I wouldn’t really care about the error since its working fine but I’m wondering if all those errors could build up and cause a performance loss somehow.

Hi! I believe the null exception is not actually referring to the player gameobject, but rather to raycast hit in the line above. When a raycast doesn’t hit any targets, its collider will default to null. A simple null check should fix this error:

if(hit.collider != null && hit.collider.gameObject == player)

This would also explain why the script still appears to work, as anytime the raycast doesn’t hit anything, you would just throw an error.

Hope this helps! :slight_smile: