2012-09-15 77 views
0

我正在製作一個庫存系統,我被卡在物品應該通過簡單的拖放來移動的部分。XNA遊戲物品拖放 - 如何實現對象交換?

有一個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; 
} 

回答

1

爲什麼不使用索引您Inventory數組:int fromCell, toCell

var temp = Inventory[toCell]; 
Inventory[toCell] = fromCell; 
Inventory[fromCell] = temp; 

您正在將庫存建模爲插槽的二維數組,因此使用索引訪問它似乎相當安全。

+0

當然,指數! – user1306322

2

這個怎麼樣?

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); 
+0

問題是,您是否可以將引用傳遞給通過索引器方法獲得的對象? – Bartosz

+0

@Bartosz爲什麼不呢? – AgentFire

+0

我的不好,當然這是可能的數組,這是不可能的自定義索引('這[索引]')。 – Bartosz