I try to build a component than inherits from StaticMeshComponent in C++
I want this component to have a default mesh. So I tried to access this mesh from AssetRegistry. But it seems that the mesh isn’t applied, event though the mesh is found.
Here is my code :
// Inherits from StaticMeshComponent !
UCLASS()
class UFocusMesh : public UStaticMeshComponent
{
public:
UFocusMesh(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
};
UFocusMesh::UFocusMesh(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
FAssetData assetData = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(FName("AssetRegistry"))
.Get()
.GetAssetByObjectPath(
FSoftObjectPath("/Script/Engine.StaticMesh'/Engine/BasicShapes/Plane.Plane'")
);
// This is correctly logged.
ULogger::Error(assetData.GetAsset()->GetClass()->GetName());
// Not working ?
this->SetStaticMesh(Cast<UStaticMesh>(assetData.GetAsset()));
}
Why this isn’t working ?
Is there a better way to set a default mesh to a staticMeshComponent in CPP ?
I do NOT know why it is not working.
I just played around a bit with your example and it is hard to test for me (I don’t have experience) because it is not a StaticMeshActor, but a StaticMeshComponent.
I switched to the default constructor,
used this code:
auto MeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Engine/BasicShapes/Cone.Cone'"));
if (MeshAsset.Object != nullptr)
{
this->SetStaticMesh(MeshAsset.Object);
this->SetGenerateOverlapEvents(true);
}
this->SetMobility(EComponentMobility::Movable);
which I got from examples from a book,
placed an actor in the world, added your component to the actor and was now able to see something.
But… I am pretty sure I created a monster because there was a 2nd object somewhere.
HORROR OBJECT LOOKING AT ME!
No, just no idea why there was a 2nd object/mesh somewhere in an otherwise empty level.
So… this is NOT your answer, it is NOT a solution, but perhaps you get an idea from it?
Btw, in your original code
SetStaticMesh returns the success (which was true with your code)
Perhaps it already works, just “Plane” is to … flat to see that it works?
Setting a mesh (or any asset) in the constructor is generally not recommended.
It will load it when the engine initializes all C++ classes at the start (the Class Default Objects, or CDOs), slowing down every editor launch.
It will be kept in memory indefinitely, even though you never use the mesh, since the CDO keeps a reference to it until the game is shut down.
It would be better to put this kind of functionality into for example the PostLoad function. Then you can check if the StaticMeshComponent is empty, and only then populate it with the default mesh.