我正在制作一个库存系统,我被困在应该通过简单的拖拽将物品从一个单元格移动到另一个单元格的部分。
有一个Item[,] Inventory
数组保存项目,object fromCell, toCell
应该保存对释放鼠标按钮时要操作的单元格的引用,但当我尝试这样做时:
object temp = toCell;
toCell = fromCell;
fromCell = temp;
游戏只是交换对象引用,而不是实际对象。我该如何做到这一点?
UPD:多亏了Bartosz,我明白了这一点。事实证明,您可以安全地使用对对象数组的引用,并使用要交换的对象的已保存索引来更改。
代码可以是这样的:
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;
}
这个怎么样?
internal static void Swap<T>(ref T one, ref T two)
{
T temp = two;
two = one;
one = temp;
}
你所有的交换都变成了这个。
Swap(Inventory[fromCell], Inventory[toCell]);
此外,您还可以为数组添加扩展(如果更舒适的话)。
public static void Swap(this Array a, int indexOne, int indexTwo)
{
if (a == null)
throw new NullReferenceException(...);
if (indexOne < 0 | indexOne >= a.Length)
throw new ArgumentOutOfRangeException(...);
if (indexTwo < 0 | indexTwo >= a.Length)
throw new ArgumentOutOfRangeException(...);
Swap(a[indexOne], a[indexTwo]);
}
这样使用:
Inventory.Swap(fromCell, toCell);
为什么不对Inventory
数组使用索引:int fromCell, toCell
。
var temp = Inventory[toCell];
Inventory[toCell] = fromCell;
Inventory[fromCell] = temp;
您将库存建模为2D插槽阵列,因此使用索引访问它似乎相当安全。