NullReferenceException, but the reference is set!

NullReferenceException: Object reference not set to an instance of an object
Squad.AddUnit (.Unit u) (at Assets/Scripts/Squad.cs:20)
UnitManager.Start () (at Assets/Scripts/UnitManager.cs:44)

I’m getting a NullReferenceException (at units.Add(u);, see below) but I can’t understand why. But by the time I’ve called AddUnit I’ve already checked that unit exists in the if statement, and done a print command with it (which prints as expected).

Here’s AddUnit in Squad:

 public List<Unit> units;
    	public bool selected=false;
    	
    	// Use this for initialization
    	void Start () {
    		
    		units=new List<Unit>();
    		print("units initialized: "+units.Count);
    	
    	}
    
    public void AddUnit(Unit u)
    	{
    		units.Add(u); //This is the line that throws the error
    	}

Here’s the only place AddUnit is called from:

public List<Squad> squads;
	public int numberOfSquads=4;
	
	
	// Use this for initialization
	void Start () {
		
		squads=new List<Squad>();
		
		for(int i=0; i<numberOfSquads;i++)
		{
			squads.Add(new Squad());//create the number of squads we need, their position in the List will be their "id"
		}
		
		foreach(GameObject go in allUnitsList)
		{
			Unit unit;
			int squadID;
			Squad squad;
			
			unit=go.GetComponent<Unit>();
			
			if(unit)//make sure we have a Unit component attached
			{
				squadID=unit.squadID;
				squad=squads[squadID];
				
				print("squad building: "+unit.gameObject.name+" goes to squad "+unit.squadID+" squad selected: "+squad.selected);
				/*squad building: PlayerUnit1_1 goes to squad 1 squad selected: False
				UnityEngine.MonoBehaviour:print(Object)
				UnitManager:Start() (at Assets/Scripts/UnitManager.cs:42)*/
				
				squad.AddUnit(unit);
				
			}
		}
	
	}

I thought maybe units wasn’t being initialized in time, so included the print to check, and it fires long before AddUnit is called. So squad, unit, and units are initialized when the function is called, so what exactly is null??

Probably the second Start() method is called before the first one.

Try doing the initialization in Awake() instead of Start():

void Awake() {

    units=new List<Unit>();
    print("units initialized: "+units.Count);

 }

Ok, figured it out. I wasn’t using Squad as a monobehavior, just a C# class, so I needed to use the normal constructor.

public class Squad {
	
	public List<Unit> units;
	public bool selected=false;
	
	public Squad()
	{
		units=new List<Unit>();
		Debug.Log("units should be init");
	}