Variables in components always returning null?

Im trying to access data from another gameobject, I’m in the position to use a reference via the inspector, but for some reason everytime I try to access the list created in the other class its ALWAYS null. I don’t get it.

Here’s the relevant pseudo-code:

public class DStarMap : MonoBehaviour
{
	
	public XDocument doc;
	public List<DStar> starList;
	
	void Start()
	{
		doc = XDocument.Load (Application.dataPath + "/Code/Data/galaxy.xml");
		starList = (from q in doc.Descendants ("Star") select new DStar{
			ID = int.Parse (q.Element("ID").Value),
			x = int.Parse (q.Element("X").Value),
			y = int.Parse (q.Element("Y").Value),
			magnitude = float.Parse (q.Element("Magnitude").Value),
			size = int.Parse (q.Element("Size").Value),
		}).ToList ();
         Debug.Log(starList.Count);
    }
}

The list has all the correct information in it if I’m debugging it in that class specifically.
And in the other class where I’m trying to get the list:

public class GalaxyMapScript: MonoBehaviour
{
	
	public GameObject Database;
	private DStarMap _starMap;
	
	void Awake()
	{
	       _starMap = Database.GetComponent<DStarMap>();
           Debug.Log(_starMap.starList.Count);
    }
}

The count is always null. I don’t understand. I’m assigning the reference to the database object through the inspector. Ugh.

It’s null because you haven’t set it to anything yet.

GalaxyMapScript’s Awake() function will run before DStarMap’s Start() function. The simplest fix would be to swap them ie set up the starList in DStarMap’s Awake() and get the reference to it in GalaxyMapScript’s Start().

But in most situations, unless there’s a real need to cache the reference within GalaxyMapScript, I would probably prefer to get rid of the _starMap variable and just use Database.starList within the GalaxyMapScript class. Sometimes though there can be a need to cache the reference (eg you want to make sure that GalaxyMapScript retains its list if Database is destroyed, or if the list in Database is set to a new List).

Make sure you initialize a ‘new instance’ of your list on every start.

public class DStarMap : MonoBehaviour
{
	
	public XDocument doc;
	public List<DStar> starList;
	
	void Start()
	{
		starList = new List<DStar>();
		//Your code here
	}
}