BitMask是使用bit来表达True或false的概念,它可以使用一个int来表达多组的功能是否启用。
先让我们来看下图:
若我们想要依照PlayerLevel跟Speed来进行排序的话,一般不知道这个技巧的人可能会使用二个int来处理这件事。在使用了BitMask之后我们就可以藉由将第一跟第三个bit设为1来表达这件事。在一般的C++中我们常常在enum的设定中就直接将该bit位移,如下面的code:
enum class EHorizonPlayerSortType { Invalidated = ( 1 << 0 ), Leve = ( 1 << 1 ), Power = ( 1 << 2 ), Speed = ( 1 << 3 ), PlaceHolder1 = ( 1 << 4 ), PlaceHolder2 = ( 1 << 5 ), PlaceHolder3 = ( 1 << 6 ), PlaceHolder4 = ( 1 << 7 ), }; void Usage (){ int flag = EHorizonPlayerSortType::Level | EHorizonPlayerSortType::Speed; }
但在UE4中的Bitmask没办法使用跟上面一样的做法,由于enum class被限制成只能使用uint8,因此在UE4中是直接将enum中的值当成位移数,如下面的code:
UENUM (BlueprintType, meta = (Bitflags)) enum class EHorizonPlayerSortType : uint8 { Invalidated = 0 , Level UMETA (DisplayName = " PlayerLevel " ), Power UMETA (DisplayName = " Power " ), Speed UMETA (DisplayName = " Speed " ), PlaceHolder1 UMETA (DisplayName = " PlaceHolder1 " ), PlaceHolder2 UMETA (DisplayName = " PlaceHolder2 " ), PlaceHolder3 UMETA (DisplayName = " PlaceHolder3 " ), PlaceHolder4 UMETA (DisplayName = " PlaceHolder4 " ), }; ENUM_CLASS_FLAGS (EHorizonPlayerSortType) USTRUCT(BlueprintType) struct HORIZONTWEEN_API FHorizonPlayerParameters { GENERATED_BODY () FHorizonPlayerParameters () : PlayerSortTypeFlags (( int )EHorizonPlayerSortType::Level) { } public: UPROPERTY (EditAnywhere, BlueprintReadWrite, meta = (Bitmask, BitmaskEnum = " EHorizonPlayerSortType " )) int PlayerSortTypeFlags; }; bool HasFlag ( const INT32& Flags, EHorizonPlayerSortType TestFlag) { INT32 bitFlag = static_cast <int32>( 1 << (INT32)TestFlag); // shift to the bit corresponding to the enum value return (Flags & bitFlag ) != 0 ; } void Usage ( const FHorizonPlayerParameters& param){ INT32 bitFlag = static_cast <int32>(( 1 << (INT32)EHorizonPlayerSortType::Level) | ( 1 << (INT32)EHorizonPlayerSortType::Speed)); // 10 bool b1 = HasFlag (param. PlayerSortTypeFlags , EHorizonPlayerSortType::Level); // true bool b2 = HasFlag (param. PlayerSortTypeFlags , EHorizonPlayerSortType::Power); // false bool b3 = HasFlag (param. PlayerSortTypeFlags , EHorizonPlayerSortType::Speed); // true }
其中
INT32 bitFlag = static_cast<int32>((1 << (INT32)EHorizonPlayerSortType::Level) |
(1 << (INT32)EHorizonPlayerSortType::Speed));
就是模拟Blueprint中选择要启用哪个enum的C++实作。