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

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

相关内容:

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

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

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

 

示例1:

动态加载Object的工具方法

Cpp代码   收藏代码
  1. UTexture2D* MyTextureLoader::LoadTextureFromPath(const FString& Path)  
  2. {  
  3.     if (Path.IsEmpty()) return NULL;  
  4.   
  5.     return Cast(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(Path)));  
  6. }  
调用:
Cpp代码   收藏代码
  1. FString PathToLoad = "/Game/Textures/YourStructureHere";  
  2. UTexture2D* tmpTexture = LoadTextureFromPath(PathToLoad);  
 

 

 

示例2:
加载MaterialTexture

Cpp代码   收藏代码
  1. struct FConstructorStatics  
  2.  {  
  3.      ConstructorHelpers::FObjectFinderOptional TextureFinder;  
  4.      ConstructorHelpers::FObjectFinderOptional 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.    
  13.  Texture = ConstructorStatics.TextureFinder.Get();  
  14.  UMaterial* Material = ConstructorStatics.MaterialFinder.Get();  
  15.  DynamicMaterial = UMaterialInstanceDynamic::Create(Material, this);  
 

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

Cpp代码   收藏代码
  1. DynamicMaterial->SetTextureParameterValue(FName("DynamicTexture"), Texture);  
  2. Mesh->SetMaterial(0, DynamicMaterial);  
 
 

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

Cpp代码   收藏代码
  1. Texture2D* mytex; //这里假设mytex合法有效  
  2.   
  3. mytex->ConditionalBeginDestroy();  
  4. mytex = NULL;  
  5. 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/nafio/p/9137068.html

你可能感兴趣的:([UE4]C++实现动态加载UObject:StaticLoadObject();以Texture和Material为例)