簡體   English   中英

虛幻引擎4 C ++更改AStaticMeshActor的StaticMeshComponent

[英]Unreal Engine 4 C++ Change StaticMeshComponent of AStaticMeshActor

我正在嘗試更改每個“靜態網格物體Actor”的“材質”屬性。 我知道我需要遍歷每個Actor並找到“靜態網格物體組件”。 但是,我無法正確修改材料。

這是我的代碼,

GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("START Modeling()"));

//Find Actor and change Material
UWorld* world = GetWorld();

//Material Path
FString matPath = "Material'/Game/StarterContent/Materials/M_Metal_Gold.M_Metal_Gold'";
//Material Instance
UMaterialInstanceConstant* material = Cast<UMaterialInstanceConstant>(StaticLoadObject(UMaterialInstanceConstant::StaticClass(), nullptr, *(matPath)));
//Iterate Every Static Mesh Actor
for (TActorIterator<AStaticMeshActor> ActorItr(world); ActorItr; ++ActorItr)
{
    AStaticMeshActor *Mesh = *ActorItr;
    //Just for Degbuging Purpose
    GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Actor: %s"), *(ActorItr->GetName())));
    GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Location: %s"), *(ActorItr->GetActorLocation().ToString())));
    //Get Static Mesh Component
    TArray<UStaticMeshComponent*> MaterialComps;
    Mesh->GetComponents(MaterialComps);
    //I get this code from community answer. I do not know how it works.
    for (int32 Index = 0; Index != MaterialComps.Num(); ++Index)
    {
        UStaticMeshComponent* targetComp = MaterialComps[Index];
        int32 mCnt = targetComp->GetNumMaterials();
        for (int i = 0; i < mCnt; i++)
                    //This is the core code which actually changing material.
            targetComp->SetMaterial(0, material);
    }

}

之前 在此處輸入圖片說明 在此處輸入圖片說明

之所以發生這種情況,是因為我要通過迭代來更改每個演員。
但是,它僅更改發言者的材料。

您僅更改索引為0的物料。

更改targetComp->SetMaterial(0, material); targetComp->SetMaterial(i, material); 它應該可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM