对于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