Download

Change static mesh of a actor using StaticLoadObject()..

I want to dynamic static mesh load system for change avatar’s weapon appearance.
So i create AAvatarEquipment actor creating default static mesh called ‘dirt’ in constructor and change it with SetWeaponStaticMesh() function below.



AAvatarEquipment::AAvatarEquipment() {
    PrimaryActorTick.bCanEverTick = false;

    StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("WEAPON"));
    RootComponent = StaticMesh;

    static ConstructorHelpers::FObjectFinder<UStaticMesh> EQUIPMENT(
        TEXT("/Game/resources/blocks/dirt"));

    if (EQUIPMENT.Succeeded()) {
        StaticMesh->SetStaticMesh(EQUIPMENT.Object);
    }
    StaticMesh->SetCollisionProfileName(TEXT("NoCollision"));
}

void AAvatarEquipment::SetWeaponStaticMesh(const FString& ContentPath) {
    UStaticMesh* NewMesh = Cast<UStaticMesh>(StaticLoadObject(
        UStaticMesh::StaticClass(), NULL, *(ContentPath)));

    if (NewMesh) {
        StaticMesh->SetStaticMesh(NewMesh);
        auto tName = StaticMesh->GetStaticMesh()->GetName();
    }
}


It called in playerController since it is utility for weapon swap so i want to change the static mesh with ‘earth’ static mesh for test.



void AABPlayerController::EquipQuickSlot01() {
    AAvatar* IPlayer = Cast<AAvatar>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));

    if (IPlayer->Weapon == nullptr) {
        FString Path = "/Game/resources/blocks/earth";

        WeaponTable = NewObject<AAvatarEquipment>();
        WeaponTable->SetWeaponStaticMesh(Path);                      // Change the static mesh with earth. 

        auto WeaponClass = WeaponTable->StaticClass();          // it load only dirt static mesh..

        if (IsValid(WeaponClass)) {
            GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Green,
                FString::Printf(TEXT("WeaponClass Valid.")));

            auto NewWeapon = GetWorld()->SpawnActor<AAvatarEquipment>(WeaponClass,
                FVector::ZeroVector, FRotator::ZeroRotator);

            FName WeaponSocket(TEXT("hands_rSocket"));
            if (NewWeapon != nullptr) {
                NewWeapon->AttachToComponent(IPlayer->GetMesh(),
                    FAttachmentTransformRules::SnapToTargetNotIncludingScale, WeaponSocket);
                GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Green,
                    FString::Printf(TEXT("WeaponSocket work well.")));

                auto tName = WeaponClass->GetName();

                GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Green,
                    FString::Printf(TEXT("Name : %s"), *tName));
            }           
        }
    }
}


However it doesn’t show earth static mesh only show dirt static mesh and it pass all of validation check using IsValid() function.
I try to don’t make actor class for each of weapon because i want to change only the appearance of weapon.