Suggestions for switching static meshes?

Hello Forum,

Having finished Battle Tank, I’ve now just begun some practice in the form of recreating Space Invaders in Unreal using C++. I’ve now come across my first obstacle.

I’m trying to recreate the effect where the aliens move every second or so and also change shape. To accomplish this, I’m trying to set the static mesh of the actor every second. However, while the following code compiles, it crashes the editor on play and the debugger points to the ConstructorHelper lines as the trouble-makers.

I’ve read online that you must use FObjectFinder in the constructor of your class but when I paste those lines there, SetStaticMesh() becomes unaware of “StaticBugOpen” and “StaticBugClosed”.

Does anyone out there know how I might fix this code or know of a better way to accomplish this effect?

void AAlien::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
MoveAlien();
}
void AAlien::MoveAlien()
{
if(GetWorld()->GetTimeSeconds() >= TimeOfLastMove + MoveDelay)
{
FVector AlienLocation = GetActorLocation();
AlienLocation.X += 20.0f;
SetActorLocation(AlienLocation, false);

    static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticBugClosed(TEXT("StaticMesh'/Game/Aliens/SpaceInvaderSprites01_BugInvaderClosed.SpaceInvaderSprites01_BugInvaderClosed'"));
    static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticBugOpen(TEXT("StaticMesh'/Game/Aliens/SpaceInvaderSprites01_BugInvaderOpen.SpaceInvaderSprites01_BugInvaderOpen'"));
    
    if(bIsAlienOpen == true)
    {
        UStaticMeshComponent().SetStaticMesh(StaticBugClosed.Object);
        bIsAlienOpen = false;
    }
    
    if(bIsAlienOpen == false)
    {
        UStaticMeshComponent().SetStaticMesh(StaticBugOpen.Object);
        bIsAlienOpen = true;
    }
    
    TimeOfLastMove = GetWorld()->GetTimeSeconds();
}

}

Cheers.

Look at the green highlighted answer

You cannot call FObjectFinder outside the contructor, that’s why you crash.

Sorry but there’s only a Blueprint solution provided and i cannot figure out how to port it into C++.

5 years too late, but since I was dealing with this today I thought I’d throw my advice in.

If you’d like to accomplish something similar, I recommend either keeping the different meshes you are going to use as variables in your .h file and instantiating them in the constructor using the FObjectFinder similarly to how you are doing here.

There is another approach that will look something like so (Using one of the basic shapes from the engine in this example):

UStaticMeshComponent* Shape;
Shape = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyBasicShape"));

UStaticMesh* ConeAsset = LoadObject<UStaticMesh>(nullptr, TEXT("StaticMesh'/Engine/BasicShapes/Cone.Cone'"));

if (ConeAsset)
{
    Shape->SetStaticMesh(ConeAsset);
}


Hope it might be of use for someone later on :slight_smile:

Privacy & Terms