Download

Suggestions for switching static meshes?

Hello Forum,

I am a 3D artist new to programming. I’ve finished over half of GameDev.tv’s C+±with-Unreal course., Now I’ve just begun some practice on my own 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.

What you can do is make variables for UStaticMesh, use constructorhelper to fill them in the constructor, and then use those variables in your BeginPlay, Tick, etc.

The best approach however would be something like this:



.h
UPROPERTY(EditAnywhere, Category = "Alien") TMap<FName, UStaticMesh*> AlienMeshes;

.cpp
AlienMeshes"firstmesh"];


Now in your editor, create a blueprint using this class as a base, and in the details panel you’ll see a variable called AlienMeshes. You can drag in a bunch of meshes and give them names, and then easily call them in the code using AlienMeshes"name"].
This is also useful since it’s not dependent on the filename anymore, so you can easily move files around, change files, etc, without having to modify the code every time.

Then why don’t you use it in your constructor, because It seems you are using this function in your Tick.
Also I assume you have some lack of knowledge about asset loading into memory, so you better check out the docs on this: