Download

Unable to SetStaticMesh inside actor BeginPlay

I’m new to UE4 and testing some basic functionalities: I want to setstaticmesh for StaticMeshComponent inside an actor but it only works if I put it inside the constructor. The same lines error when put inside beginplay. Am I doing something wrong?



#include "HexMapGenerator.h"

// Sets default values
AHexMapGenerator::AHexMapGenerator()
{
    // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = false;

    BaseMesh = CreateDefaultSubobject<UStaticMeshComponent>("HexMesh");
    RootComponent = BaseMesh;
    static ConstructorHelpers::FObjectFinder<UStaticMesh> MeshAsset(TEXT("/Game/MyContent/Meshes/HexTileBase.HexTileBase"));
    if (MeshAsset.Succeeded()) {
        BaseMesh->SetStaticMesh(MeshAsset.Object);
    }
}


The above works. As soon as I compile and run the project, the static mesh is set for the static mesh component as seen in the editor



// Called when the game starts or when spawned
void AHexMapGenerator::BeginPlay()
{
    Super::BeginPlay();

    static ConstructorHelpers::FObjectFinder<UStaticMesh> MeshAsset(TEXT("/Game/MyContent/Meshes/HexTileBase.HexTileBase"));
    if (MeshAsset.Succeeded()) {
        BaseMesh->SetStaticMesh(MeshAsset.Object);
    }
}


The above doesnt work. Visual Studio errors after I drop the actor into the level and hit play.

I solved this by declaring a new private variable in the header file and assigning its value in the constructor.



private:
    UStaticMesh* Mesh;


and then setstaticmesh in beginplay. It seems like asset reference lookup works in constructor but not in beginplay for some reason:



AHexMapGenerator::AHexMapGenerator()
{
    // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = false;

    BaseMesh = CreateDefaultSubobject<UStaticMeshComponent>("HexMesh");
    RootComponent = BaseMesh;
    static ConstructorHelpers::FObjectFinder<UStaticMesh> MeshAsset(TEXT("/Game/MyContent/Meshes/HexTileBase.HexTileBase"));
    if (MeshAsset.Succeeded()) {
        Mesh = MeshAsset.Object;
    }
}

// Called when the game starts or when spawned
void AHexMapGenerator::BeginPlay()
{
    Super::BeginPlay();
    if (Mesh != nullptr)
        BaseMesh->SetStaticMesh(Mesh);
}