Enum returns null reference exception

I don’t know how I didn’t notice this but the issue was I was checking to see if the troop existed after I already was referencing the troop.

I’m trying to compare two enums on two different game objects.

            if ( (int)troop.GetComponent<Team>().team == (int)team.team )
            {
                continue;
            }


But this code returns a null reference exception. Why is this? I have the team variable assigned in the inspector.

Team script:

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

public class Team : MonoBehaviour
{
    public enum TeamColor {Red, Blue, Yellow, Pink, Green, Orange};
    public TeamColor team;
}

Rest of the other script:

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

public class Gunner : MonoBehaviour
{
    public float fireRate;
    public float range = 10;
    public float damage;
    public GameObject bullet;
    public float bulletSpeed;
    public Transform gunTip;
    public Team team;
  
    private float nextFireTime;
  
    private void FixedUpdate()
    {
        if ( Time.time < nextFireTime )
        {
            return;
        }

        Collider[] hitCols = Physics.OverlapSphere(transform.position, range);

        foreach ( Collider col in hitCols )
        {
            Troop troop = col.GetComponent<Troop>();

            if ( (int)troop.GetComponent<Team>().team == (int)team.team )
            {
                continue;
            }

            if ( troop )
            {
                Instantiate(bullet, gunTip.transform.position, gunTip.transform.rotation);
                bullet.transform.LookAt(col.transform);
                bullet.GetComponent<Bullet>().speed = bulletSpeed;

                nextFireTime = Time.time + fireRate;      
            }
        }
      
    }
}

Break it up to find out!

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

Putting lots of code on one line DOES NOT make it any faster. That’s not how compiled code works.

The longer your lines of code are, the harder they will be for you to understand them.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

Remember, NO MATTER WHAT, the answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that
2 Likes

You’re checking a hit collider for a Team component that doesn’t have one.

2 Likes

This line:

Has a total of 3 potential things that could be null:

  • Your troop variable may be null, so of course you can not call GetComponent on it. Since you get your troop variable from another GetComponent call, that GetComponent call may already return a null value because there’s no such component on the same gameobject as the collider.
  • Your troop component may exist, so you can call GetComponent<Team>() on it, but there may be no such component on the same gameobject as your Troop script. So GetComponent could return null, so accessing the team would fail / cause a null reference exception.
  • Assuming the first two are actually valid, in the end you compare the team of the Troop object against team.team. If that team variable does not reference any Team instance (anymore?), you would again get a null reference exception when you try to access the team field.

So 3 things that could be null. It’s your job to either ensure that they are not null, or you have to explicitly check them for non-null values before you go any further.

2 Likes

What also wasn’t pointed out which is pertinent is that an enum is a value type, so it’s impossible for the enum specifically to be null.

This kind of stuff is why it’s good to get into the habit of using TryGetComponent<T>(out T) over GetComponent<T>.

2 Likes

Enums cannot be null, they’re value types, so they cannot throw an NRE (unless you’re using a Nullable i.e. Enum?). So you basically need to check the “Team” objects.