Thursday, June 16, 2022
HomeGame Developmentunity - Hassle including to a dictionary utilizing a for loop

unity – Hassle including to a dictionary utilizing a for loop


I am making an attempt to create a hotbar system the place you possibly can press 1 via 0 to activate skills positioned within the hotbar slots. As a substitute of a large block of if/else statements I need to make a single test that may match the GameObjects within the array “Slots” with an related KeyCode. To try this I made a easy for loop that provides a pair.

When I attempt to run the next code, I get the error NullReferenceException: Object reference not set to an occasion of an object. I might assume which means that the article Slots[i] does not exist, nevertheless it undoubtedly does for each iteration of the loop; I made 10 empty “slot” objects which are youngsters of the Hotbar Object that runs this script.

This is the code:

[SerializeField]GameObject[] Slots;
Dictionary<GameObject, KeyCode> SlotKey;

void Begin()
{
    for (int i = 0; i < 10; ++i)
    {
        print(Slots[i].identify);
        SlotKey.Add(Slots[i], (KeyCode)i + 48);
    }
}

When this code runs, it prints solely the identify of the primary object in Slots (slot 0) after which offers me the error message. Operating this loop with solely the print works appropriately, printing the names of slots 0 via 9. I additionally tried a foreach model:

    int i = 0;
    foreach (GameObject s in Slots)
    {     
        print(s.identify + (KeyCode)(i + 48));
        SlotKey.Add(s, (KeyCode)(i + 48));
        
        i++;
    }

This resulted in the very same problem the place each a part of this loop works appropriately aside from SlotKey.Add.

Why does my dictionary appear unable to seek out the gameobjects in my array when the for loop itself appears to don’t have any hassle with it?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments