Unreal Engine 4:如何使用C++动态设置Material

首先,加载Material

方式一:

class UMaterial* ColorMaterial;

ColorMaterial = ConstructorHelpers::FObjectFinderOptional(TEXT("Material'/Game/Materials/ColorMaterial.ColorMaterial'")).Get();

方式二:

class UMaterial* ColorMaterial;

static ConstructorHelpers::FObjectFinder ColorMaterial_Finder(TEXT("Material'/Game/Materials/ColorMaterial.ColorMaterial'"));
if (ColorMaterial_Finder.Object)
{
  ColorMaterial = (UMaterial*)ColorMaterial_Finder.Object;
}

然后,针对component创建动态MaterialInstance

class UStaticMeshComponent* smc;  // 需要在此component上设置Material

class UMaterialInstanceDynamic* ColorMaterial_Inst = UMaterialInstanceDynamic::Create(ColorMaterial, smc);

如果上需要设置一些变量值的话,可通过如下代码设置:

ColorMaterial_Inst->SetVectorParameterValue(FName(TEXT("LightColor")),FLinearColor(0.0,0.0,0.0,1.0);

最后,在component上设置MaterialInstance

smc->SetMaterial(0, ColorMaterial_Inst);

参考文档

Change material parameter from c++
Edit Material Parameters C++

你可能感兴趣的:(C++,Unreal,Engine,4)