I'm trying to create a hotbar system where you can press 1 through 0 to activate abilities placed in the hotbar slots. Instead of a giant block of if/else statements I want to make a single check that can match the GameObjects in the array "Slots" with an associated KeyCode. To do that I made a simple for loop that adds a pair.
When I try to run the following code, I get the error NullReferenceException: Object reference not set to an instance of an object. I would assume this means that the object Slots[i] doesn't exist, but it definitely does for every iteration of the loop; I made 10 empty "slot" objects that are children of the Hotbar Object that runs this script.
Here's the code:
[SerializeField]GameObject[] Slots;
Dictionary<GameObject, KeyCode> SlotKey;
void Start()
{
for (int i = 0; i < 10; ++i)
{
print(Slots[i].name);
SlotKey.Add(Slots[i], (KeyCode)i + 48);
}
}
When this code runs, it prints only the name of the first object in Slots (slot 0) and then gives me the error message. Running this loop with only the print works correctly, printing the names of slots 0 through 9. I also tried a foreach version:
int i = 0;
foreach (GameObject s in Slots)
{
print(s.name + (KeyCode)(i + 48));
SlotKey.Add(s, (KeyCode)(i + 48));
i++;
}
This resulted in the exact same issue where every part of this loop works correctly except for SlotKey.Add.
Why does my dictionary seem unable to find the gameobjects in my array when the for loop itself seems to have no trouble with it?
print
line occurred before theSlotKey.Add()
line, rather than after, as you've shown here. Unless the error message is different than the one you've quoted. \$\endgroup\$