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;
}
}
}
}
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.
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.