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

相关内容:

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

http://aigo.iteye.com/blog/2281558
C++静态加载问题:ConstructorHelpers::FClassFinder()和FObjectFinder() 

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

示例1:

动态加载Object的工具方法

UTexture2D* MyTextureLoader::LoadTextureFromPath(const FString& Path)  
{  
    if (Path.IsEmpty()) return NULL;  
  
    return Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(Path)));  
}  

调用:

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

示例2:
加载MaterialTexture

struct FConstructorStatics  
 {  
     ConstructorHelpers::FObjectFinderOptional<UTexture> TextureFinder;  
     ConstructorHelpers::FObjectFinderOptional<UMaterial> MaterialFinder;  
     FConstructorStatics()  
         : TextureFinder(TEXT("Texture2D'/Game/Textures/2DBackground.2DBackground'"))  
         , MaterialFinder(TEXT("Material'/Game/Materials/DynamicTextureMaterial.DynamicTextureMaterial'"))  
     {  
     }  
 };  
 static FConstructorStatics ConstructorStatics;  
   
 Texture = ConstructorStatics.TextureFinder.Get();  
 UMaterial* Material = ConstructorStatics.MaterialFinder.Get();  
 DynamicMaterial = UMaterialInstanceDynamic::Create(Material, this);  

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

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

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

Texture2D* mytex; //这里假设mytex合法有效  
  
mytex->ConditionalBeginDestroy();  
mytex = NULL;  
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

原文地址:https://www.cnblogs.com/timy/p/8622791.html