對於C++定義的Enum類型,可以使用以下代碼:
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("Your_Enum_Name"), true);
來獲取UEnum指針,這里的ANY_PACKAGE參數,也可以是自己確定的某一個UPackage指針
但對於在藍圖中定義的枚舉類型,使用上述代碼,返回的卻是空指針,即獲取失敗了,
通過深入跟蹤UE源碼,調用上述代碼時候,發現其已經獲取到UObject了,卻返回來一個空指針,所以有點奇怪,源碼調用堆棧如下:
但下面的代碼,一堆if條件判斷卻不滿足,所以最終還是返回了nullptr
if /* check that the name matches the name we're searching for */ ((Object->GetFName() == ObjectName) /* Don't return objects that have any of the exclusive flags set */ && !Object->HasAnyFlags(ExcludeFlags) /* check that the object has the correct Outer */ && Object->GetOuter() == ObjectPackage /** If a class was specified, check that the object is of the correct class */ && (ObjectClass == nullptr || (bExactClass ? Object->GetClass() == ObjectClass : Object->IsA(ObjectClass))) /** Include (or not) pending kill objects */ && !Object->HasAnyInternalFlags(ExclusiveInternalFlags)) { 。。。。。 }
通過代碼分析,以及查看Object的類型,發現它是個UUserDefinedEnum類型,可能不滿足UEnum ObjectClass的判斷條件,所以,把FindObject<UEnum>改成FindObject<UUserDefinedEnum>,終於成功獲取到了藍圖定義的枚舉類型。
分析UE的類圖(圖片來源知乎):
UUserDefinedEnum派生於UEnum,理論上來說,使用FindObject<UEnum>是沒問題的,但UE源碼中直接使用GetClass() == ObjectClass,導致失敗了,或許bExactClass改成false也可以吧
本人知乎地址:
https://zhuanlan.zhihu.com/p/432058792