I’m making an inventory system and I’m stuck at the part where the items should be moved from cell to cell by simple drag’n’dropping.
There is an Item[,] Inventory array which holds the items, object fromCell, toCell which should hold the references to cells to operate with when mouse button is released, but when I try doing this:
object temp = toCell;
toCell = fromCell;
fromCell = temp;
…the game is only swapping object references and not the actual objects. How do I make this work?
UPD: Thanks to Bartosz I figured this out. Turns out you can safely use a reference to array of objects and change it with saved indices of objects you wish to swap.
Code can be like this:
object fromArray, toArray;
int fromX, fromY, toX, toY;
// this is where game things happen
void SwapMethod()
{
object temp = ((object[,])toArray)[toX, toY];
((object[,])toArray)[toX, toY] = ((object[,])fromArray)[fromX, fromY];
((object[,])fromArray)[fromX, fromY] = temp;
}
Why not using indexes to your
Inventoryarray:int fromCell, toCell.You’re modeling inventory as 2D array of slots, so it seems fairly safe to use indexes to access it.