相关内容:
C++实现动态加载的问题:LoadClass<T>()和LoadObject<T>()
http://aigo.iteye.com/blog/2281558
C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例
http://aigo.iteye.com/blog/2268056
这里说的静态加载指的是必须在构造函数中完成的加载方式,动态加载值得是可以在Runtime期间加载的方式,UE4源码里面,前者其实是对后者的一层封装,即FObjectFinder()是对LoadClass()的封装。
如果要获取某个蓝图BP的类型class,可以通过ConstructorHelpers::FClassFinder()来获取,例如:
static ConstructorHelpers::FClassFinder<AActor> UnitSelector(TEXT("Blueprint'/Game/MyProject/MyBlueprint.MyBlueprint'")); TSubclassOf<AActor> UnitSelectorClass = UnitSelector.Class;
但是在启动游戏时会报错提示找不到文件,例如:
Default property warnings and errors:
Error: COD Constructor (MyGameMode): Failed to find /Game/MyProject/MyBlueprint.MyBlueprint
解决办法有两种(这是UE4的一个坑,浪费了我很长时间。。。):
A,在copy reference出来的文件路径后面加_C,例如:Blueprint'/Game/Blueprints/MyBlueprint.MyBlueprint_C'
static ConstructorHelpers::FClassFinder<AActor> UnitSelector(TEXT("Blueprint'/Game/Blueprints/MyBlueprint.MyBlueprint_C'")); TSubclassOf<AActor> UnitSelectorClass = UnitSelector.Class;
B,去掉路径前缀:/Game/Blueprints/MyBlueprint
static ConstructorHelpers::FClassFinder<AActor> UnitSelector(TEXT("/Game/Blueprints/MyBlueprint")); TSubclassOf<AActor> UnitSelectorClass = UnitSelector.Class;
另外, FClassFinder<T>()函数中的模版名必须和TSubclassOf<T>变量的模版名一样,例如上面的都是AActor,如果不一样,也会出现上面的错误。
再给个例子:
static ConstructorHelpers::FClassFinder<UUserWidget> TestBP(TEXT("/Game/Blueprints/MyWidget_BP")); TSubclassOf<UUserWidget> MyWidgetClass = TestBP.Class;
之前看到很多例子是通过FObjectFinder()来获取class,现在想想感觉是无奈之举,UE4的文档比较坑,不仅蓝图的文档更新不同步,C++的文档更是少得可怜。
static ConstructorHelpers::FObjectFinder<UBlueprint> UnitSelector(TEXT("Blueprint'/Game/MyProject/MyBlueprint.MyBlueprint'")); TSubclassOf<AActor> UnitSelectorClass = (UClass*)UnitSelector.Object->GeneratedClass;
其他参考:
CDO Constructor: Failed to find Blueprint
https://answers.unrealengine.com/questions/84880/cdo-constructor-failed-to-find-blueprint-ue-44.html