How to get List from other class

I have Inventory.cs script:

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

public class Inventory : MonoBehaviour {

    public List<Item> inventoryItems;

	void Start () {
        inventoryItems = new List<Item>();
	}
}

public class Item
{
    private string name;
    private int quantity;

    public string Name { get { return name; } set { name = value; } }
    public int Quantity { get { return quantity; } set { quantity = value; } }
}

Everything is working. But when i try to get inventoryItems list from other class i get: Object reference not set to an instance of an object.

InventoryGUI.cs script:

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

public class InventoryGUI : MonoBehaviour
{

    public GameObject player;
    public Inventory inventory;

    void Start()
    {
        inventory = player.GetComponent<Inventory>();

        Debug.Log(inventory.inventoryItems.Count);
        
    }
}

I can get int or float from Inventory.cs script. But how can i get inventoryItems list?

Couple of things could be happening.

  1. Player could be null, the assumption is that you assign this in the inspector and it’s not, but who knows.
  2. inventoryItems is null. This is probably happening do to the order in which the scripts are executed or enabled in the scene. You see if InventoryGUI is created before Inventory, then the Start function/method would try and get the Component and access the field from Inventory and it would be a null object. If you go and change the script execution order and insure Inventory exists before, or do this through other means(instantiate, etc.).

We can rule out that isn’t null, unless there is a place where you are explicitly setting inventoryItems to null, but in Start you are instantiating it. Perhaps put the instantiation of the List into an Awake function/method instead? Or inline the instantiation of the list.

public List<Item> inventoryItems = new List<Item>();

//Initialise your Class
public Inventory inventory = new Inventory();