Variable as class type on switch statement

Hello,

I am trying to make a switch statement on an enum assign a derived class type to a variable.
This way I could just say GetComponents() instead of this mess here.

Appreciate any thoughts or recommendations,
Alex

Type t = new ChessPiece().GetType();


        // ROOKS
        if (currentMovePiece == GamePiece.Rook)
        {
            t = Rook;
            moved = TryToMove(GetComponentsInChildren<t>());
        }

        // QUEENS
        if (currentMovePiece == GamePiece.Queen)
        {
            moved = TryToMove(GetComponentsInChildren<Queen>());
        }

        // KINGS
        if (currentMovePiece == GamePiece.King)
        {
            moved = TryToMove(GetComponentsInChildren<King>());
        }

Why not just use the non-generic GetComponentsInChildren(type) method? Combine that with a Dictionary<enum, Type> and that should clean up a lot of switch statements.

1 Like

You did it my friend, thank you! Now, I only need one line to handle every case :slight_smile:

Dictionary<GamePiece, Type> PieceToType = new Dictionary<GamePiece, Type>
    {
        {GamePiece.Pawn, typeof(Pawn)},
        {GamePiece.Knight, typeof(Knight)},
        {GamePiece.Bishop, typeof(Bishop)},
        {GamePiece.Rook, typeof(Rook)},
        {GamePiece.Queen, typeof(Queen)},
        {GamePiece.King, typeof(King)}
    };

    void MoveCurrentPiece()
    {
        bool moved = false;

        moved = TryToMove(GetComponentsInChildren(PieceToType[currentMovePiece]));
      
    }

    bool TryToMove(Component[] pieces)
    {
        foreach(ChessPiece p in pieces)
        {
            if (p.mySide != currentTurnSide) continue;
            if (p.AttemptMoveToPosition(currentMoveFile, currentMoveRank, capturing))
            {
                if (originalFile != 0 && p.originalFile != originalFile)
                {
                    return false;
                }
                return true;
            }
        }

        return false;
    }
1 Like