0

在庫システムを作成していますが、アイテムを単純なドラッグ アンド ドロップでセルからセルに移動する必要がある部分で立ち往生しています。

マウスボタンが離されたときに操作するセルへの参照を保持する必要があるアイテムを保持する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;
}
4

2 に答える 2

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);
于 2012-09-16T10:44:36.093 に答える
1

Inventory配列にインデックスを使用しない理由: int fromCell, toCell

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

在庫をスロットの2D配列としてモデル化しているため、インデックスを使用して在庫にアクセスするのはかなり安全なようです。

于 2012-09-15T20:44:11.483 に答える