Object reference not set to an instance of an object. No idea why

Hi!

I am getting the error “NullReferenceException: Object reference not set to an instance of an object” on this line:

if (hit.transform.gameObject.tag == "Enemy")

I don’t understand why I get the error on the line. The whole chunk of code:

RaycastHit2D hit = Physics2D.Raycast(transform.position, shootPosition.forward, 10.0f, weaponSettings.hitLayer);

            if (hit != null)
            {
                if (hit.transform.gameObject.tag == "Enemy")
                {
                    hit.transform.gameObject.GetComponent<Enemy>().DoDamage(weaponSettings.damage);

                    Vector3 particlePos = new Vector3(hit.point.x, hit.point.y, -5);
                    Instantiate(particles.bloodParticles, particlePos, Quaternion.identity);
                }
            }

If you know why I am getting this error, please tell me!

Thanks in advance.

Hey, so from the compiler’s point of view, any of these could be null that are causing the issue:

hit
hit.transform
hit.transform.gameObject
hit.transform.gameObject.tag

Since you’re checking ‘hit’ correctly. It’s any of the other 3 options.

The issue is actually with your if statement check. To check if a hit has occurred, I believe you have to check if the collider is null (or check the transform):

if (hit.collider != null) {

You’re checking if it doesn’t give you a result. Which it does, it just says it hasn’t hit anything.