【UE4】在组件中创建动态材质(C++)

创建自定义材质
【UE4】在组件中创建动态材质(C++)_第1张图片
在组件的C++文件中编写代码

在构造函数中设置静态材质

//加载自定义材质
static ConstructorHelpers::FObjectFinder<UMaterial> MaterialFinder(TEXT("Material'/Game/Materials/SelfSpriteMaterial.SelfSpriteMaterial'"));
if(MaterialFinder.Succeeded())
{
	SetMaterial(0, MaterialFinder.Object);
}

在BeginPlay()函数中设置动态材质。(否则由C++类衍生出的蓝图类将无法保存)

UMaterial* ComponentMaterial = Cast<UMaterial>(GetMaterial(0));
if(ComponentMaterial != nullptr)
{
	//创建动态材质
	ColorMaterialDynamic = this->CreateDynamicMaterialInstance(0, ComponentMaterial, FName("DynamicMaterial"));
	//ColorMaterialDynamic = UMaterialInstanceDynamic::Create(MaterialFinder.Object, this, FName("DynamicMaterial"));
	if(ColorMaterialDynamic != nullptr)
	{
		int32 Index;
		//初始化变量,不然后面设置变量会报EXCEPTION_ACCESS_VIOLATION reading address错误
		ColorMaterialDynamic->InitializeVectorParameterAndGetIndex(FName(TEXT("BaseColor")),  FLinearColor(1.0f, 0.0f, 0.0f, 1.0f), Index);
		//动态设置变量
		//ColorMaterialDynamic->SetVectorParameterValue(FName(TEXT("BaseColor")), FLinearColor(1.0f, 0.0f, 0.0f, 1.0f));
		//设置动态材质
		SetMaterial(0, ColorMaterialDynamic);
	}
}

你可能感兴趣的:(问题解决,异常修复,编程技术,ue4,材质,c++)