Trying to get Info about Slots in a Grid

Been trying to wrap my head around this for a couple of days now,
And I can’t, for the life of me, figure out, what I’m doing wrong.

So here’s the Set-Up:

I’ve got a List of Slots, which are placed in a Grid,

I then want to spawn an Item in, and set all the occupied slots to ‘occupied’.

            for (int sIndex = 0; sIndex < slots.Count; sIndex++)
            {
                Debug.Log("sIndex: " + sIndex);
                if (!slots[sIndex].occupied)
                {
                    Debug.Log("Found Empty Slot: " + sIndex);

                    Vector2Int currentSlotPos = slots[sIndex].gridPos;
                    Debug.Log(currentSlotPos);


                    for (int y = currentSlotPos.y; y < itemToAdd.itemSize.y; y++)
                    {
                        Debug.Log("Checking Row No. " + y);

                        for(int x = currentSlotPos.x; x < itemToAdd.itemSize.x + pouches[pIndex].gridSize.x * y; x++)
                        {
                            if ((x > (currentSlotPos.x + itemToAdd.itemSize.x * y) - 1))
                                continue;

                            Debug.Log("Setting Slot at Pos: " + x + ";" + y + " to occupied");

                            pouches[pIndex].slots[x].occupied = true;
                        }

                      
                    }


                    Debug.Log("Spawning Item");

                    return;
                }
            }

Here’s an example of the Inventory:
7004147--828062--upload_2021-4-4_2-31-24.png7004147--828059--upload_2021-4-4_2-28-22.png

In this example, the Slots 0,0; 1,0; 2,0; 3,0 0,1 and 1,1 get set to ‘occupied’
But only the Slots 0,0; 1,0; and 0,1; 1,1 should get set ti ‘occupied’.

How can I change my code, to not change the Slots 2,0 and 3,0 to occupied?

Thanks in advance!

By using a one-dimensional array to store the slots, you’re forcing yourself to combine the x and y into that single index. I think that’s the part that is missing.

Usually a one-dimensional index is calculated as:

int index = x + y * SpanWidth;

Are you aware that you can straight-up use 2-dimensional arrays in C#? I see your slots above is likely a List, but if it can be a 2D array, they’re pretty spiffy and would work well for this type of application and get you out of having to do the span multiplies.

MySlot[,] slots = new slots[ Across, Down];

After that you just use it as slots[x,y] directly.

If you want to know how big one of those dimensions are, instead of the .Length or .Count property, you use the .GetLength(n)

2 Likes

Using a List, because I’m more familiar with those,

will try to use an 2d array.