0

PlayerIndex とその使用方法について質問があります。

問題は、2 番目のコントローラー (controllingPlayer2) が「null」である必要がある場合があることです (たとえば、1 人のプレイヤー モードの場合) が、GetState は null 変数を受け入れることができません。

次のようなクラス(ゲーム画面用)があります:

    public GameScreen(PlayerIndex? controllingPlayer, PlayerIndex? controllingPlayer2)
    {
        this.ControllingPlayer = controllingPlayer;
        this.ControllingPlayer2 = controllingPlayer2;
    }

    public override void HandleInput()
    {
        // Move the character UP - Problem appears at the GetState Here wanting a PlayerIndex not a null?
        if (GamePad.GetState(ControllingPlayer).IsButtonDown(controls.BUp))
        {
            P1movementY--;
        }

        // Move the second character UP - Problem appears at the GetState Here wanting a PlayerIndex not a null?

        if (GamePad.GetState(ControllingPlayer).IsButtonDown(controls.BUp))
        {
            P2movementY--;
        }
4

3 に答える 3

1

&& と一緒に使用して、早期にブロックする場合に短絡します

    if (ControllingPlayer2 != null && GamePad.GetState(ControllingPlayer2).IsButtonDown(controls.BUp))
    {
        P2movementY--;
    }
于 2012-05-30T16:47:46.107 に答える
1

簡単な答え、(ControllingPlayer != null) かどうかを確認してから、ControllingPlayer.Value を使用します。

より長い形式、C# の疑問符構文を使用すると、null が割り当て可能な値ではない値の型を null として渡すことができます。これは Nullable< PlayerIndex > の省略形であり、HasValue:bool や Value:PlayerIndex などのいくつかのプロパティがあります。これは、型の非 Nullable バージョンと実際には同じではありません。

于 2012-05-30T16:50:24.010 に答える
1

Nullable の仕組みはこちらで確認できます。

public override void HandleInput()
{
    if (ControllingPlayer.HasValue && GamePad.GetState(ControllingPlayer.Value).IsButtonDown(controls.BUp))
    {
        P1movementY--;
    }

    if (ControllingPlayer2.HasValue && GamePad.GetState(ControllingPlayer2.Value).IsButtonDown(controls.BUp))
    {
        P2movementY--;
    }
}
于 2012-05-30T17:01:00.747 に答える