UE4 API 创建材质
#include "Factories/MaterialFactoryNew.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Materials/MaterialExpressionMultiply.h"
#include "Materials/MaterialExpressionTextureCoordinate.h"
#include "Materials/MaterialExpressionAppendVector.h"
#include "Materials/MaterialExpressionScalarParameter.h"
FString MaterialBaseName = "M_Material";
FString PackageName = "/Game/mat/";
PackageName += MaterialBaseName;
UPackage* Package = CreatePackage(NULL, *PackageName);
// create an unreal material asset
auto MaterialFactory = NewObject<UMaterialFactoryNew>();
UMaterial* UnrealMaterial = (UMaterial*)MaterialFactory->FactoryCreateNew(UMaterial::StaticClass(), Package, *MaterialBaseName, RF_Standalone | RF_Public, NULL, GWarn);
FAssetRegistryModule::AssetCreated(UnrealMaterial);
Package->FullyLoad();
Package->SetDirtyFlag(true);
// Tiling system
UMaterialExpressionMultiply* Multiply = NewObject<UMaterialExpressionMultiply>(UnrealMaterial);
UnrealMaterial->Expressions.Add(Multiply);
// Diffuse
FStringAssetReference DiffuseAssetPath("/Game/mat/texture/texture");
UTexture* DiffuseTexture = Cast<UTexture>(DiffuseAssetPath.TryLoad());
if (DiffuseTexture)
{
// make texture sampler
UMaterialExpressionTextureSample* TextureExpression = NewObject<UMaterialExpressionTextureSample>(UnrealMaterial);
TextureExpression->Texture = DiffuseTexture;
TextureExpression->SamplerType = SAMPLERTYPE_Color;
UnrealMaterial->Expressions.Add(TextureExpression);
UnrealMaterial->BaseColor.Expression = TextureExpression;
// Tiling
TextureExpression->Coordinates.Expression = Multiply;
}
// Tiling
UMaterialExpressionAppendVector* Append = NewObject<UMaterialExpressionAppendVector>(UnrealMaterial);
UnrealMaterial->Expressions.Add(Append);
Multiply->B.Expression = Append;
UMaterialExpressionTextureCoordinate* TexCoords = NewObject<UMaterialExpressionTextureCoordinate>(UnrealMaterial);
UnrealMaterial->Expressions.Add(TexCoords);
Multiply->A.Expression = TexCoords;
UMaterialExpressionScalarParameter* XParam = NewObject<UMaterialExpressionScalarParameter>(UnrealMaterial);
UMaterialExpressionScalarParameter* YParam = NewObject<UMaterialExpressionScalarParameter>(UnrealMaterial);
UnrealMaterial->Expressions.Add(XParam);
UnrealMaterial->Expressions.Add(YParam);
XParam->ParameterName = "TextureRepeatX";
XParam->DefaultValue = 1;
YParam->ParameterName = "TextureRepeatY";
YParam->DefaultValue = 1;
Append->A.Expression = XParam;
Append->B.Expression = YParam;
// let the material update itself if necessary
UnrealMaterial->PreEditChange(NULL);
UnrealMaterial->PostEditChange();
this->SetMaterial(0, UnrealMaterial);
以上代码生成的材质如下图所示: