相关内容:

C++实现动态加载的问题:LoadClass<T>()和LoadObject<T>()

​http://aigo.iteye.com/blog/2281558​

C++静态加载问题:ConstructorHelpers::FClassFinder()和FObjectFinder() 

​http://aigo.iteye.com/blog/2281373​


示例1:

动态加载Object的工具方法

Cpp代码 [UE4]C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例_动态加载


  1. UTexture2D* MyTextureLoader::LoadTextureFromPath(const FString& Path)
  2. {
  3. if (Path.IsEmpty()) return NULL;

  4. return Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(Path)));
  5. }

调用: Cpp代码 [UE4]C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例_动态加载


  1. FString PathToLoad = "/Game/Textures/YourStructureHere";
  2. UTexture2D* tmpTexture = LoadTextureFromPath(PathToLoad);




示例2:

加载MaterialTexture

Cpp代码 [UE4]C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例_动态加载


  1. struct FConstructorStatics
  2. {
  3. ConstructorHelpers::FObjectFinderOptional<UTexture> TextureFinder;
  4. ConstructorHelpers::FObjectFinderOptional<UMaterial> MaterialFinder;
  5. FConstructorStatics()
  6. : TextureFinder(TEXT("Texture2D'/Game/Textures/2DBackground.2DBackground'"))
  7. , MaterialFinder(TEXT("Material'/Game/Materials/DynamicTextureMaterial.DynamicTextureMaterial'"))
  8. {
  9. }
  10. };
  11. static FConstructorStatics ConstructorStatics;

  12. Texture = ConstructorStatics.TextureFinder.Get();
  13. UMaterial* Material = ConstructorStatics.MaterialFinder.Get();
  14. DynamicMaterial = UMaterialInstanceDynamic::Create(Material, this);


设置调用加载好的Material和Texture:

Cpp代码 [UE4]C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例_动态加载


  1. DynamicMaterial->SetTextureParameterValue(FName("DynamicTexture"), Texture);
  2. Mesh->SetMaterial(0, DynamicMaterial);


如果资源永不再使用,想销毁资源对象,代码如下:

Cpp代码 [UE4]C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例_动态加载


  1. Texture2D* mytex; //这里假设mytex合法有效

  2. mytex->ConditionalBeginDestroy();
  3. mytex = NULL;
  4. GetWorld()->ForceGarbageCollection(true);




Dynamic Asset Loading with C++

​https://www.youtube.com/watch?v=pJIAmSGxfmQ​


Dynamic Load Object

​https://wiki.unrealengine.com/Dynamic_Load_Object​