C# Making a List from a Dictionary, null reference

Hello there. I’m currently trying to set up an inventory system but am having problems. I’m planning on putting all my items in a JSON database, but know nothing of that and for the time being am just trying to get it working using a dictionary.

Anyway, I have a few items defined using a static Dictionary called items, here’s the code. (Weapon is a child of a class called Items, by the way.):

public class ItemList : MonoBehaviour {
	public static Dictionary<string, Item> items;
	void Start () {
		items = new Dictionary<string, Item>();
		items.Add( "sword", new Weapon("sword", 1, true, false, 1));
        items.Add( "axe", new Weapon("axe", 2, true, false, 1));
	}
}

In the script that sets up my item inventory I have the following code:

public class PlayerIO : MonoBehaviour {
	List<Item> actionBar;
	void Start () {
		actionBar = new List<Item>();
		actionBar.Add(ItemList.items["sword"]);
        }
}

But I keep getting “NullReferenceException: Object reference not set to an instance of an object” on the line with “actionBar.Add(ItemList.items[“sword”]);” when I run it in Unity.
Unfortunately I don’t know enough about lists/dictionaries other than what the single video on Unity’s site taught because I can’t find any documentation. Any help is sincerely appreciated!

The issue is due that your PlayerIO script is called before your ItemList script.
So when PlayerIO tries to look in the ItemList, it is not yet created, and then crash.

  1. A good way to initialize inner attributes (like your dictionary) is to put the given code in the Awake method instead of the Start method.

  2. Another option is to change the execution order of your script (but I don’t recommend it as it can create other problems)
    To do that:

  3. Go to: Edit menu => Project Settings => Script Execution Order

  4. Then in the inspector view hit the “plus” sign and add your two scripts (PlayerIO and ItemList)

  5. Then drag the ItemList widget before the PlayerIO

  6. Now you should have your expected behavior

ps: sorry for my writing, english is not my native tongue