Download

Getting StaticMeshComponent in C++ from Blueprint Class without making a instance of it?

Hello people,

My Goal:
I’m doing a basic Build System of Buildings. And I need in the **Builder **class to get the StaticMesh of the StaticMeshComponent (named BuildingMesh) of the **Building **Blueprint class so that I can Create **StaticMeshComponent **of the **Builder **with the Mesh of the building in order to visualize where it is going to be build and is it allowed to build or not on the pointed place. So the mesh of the **BuildingMesh **is set in the **Blueprint because I want to be able to change it just from the Blueprint if I need at some point without changing the code. **I have a C++ class of the **Building **as well in which I get the **BuildingMesh **as follows:


    TArray<UActorComponent*> StaticMeshComponents = GetComponentsByClass(UStaticMeshComponent::StaticClass());
    for (UActorComponent* StaticMeshComponent : StaticMeshComponents)
    {
        if (StaticMeshComponent->GetName() == "BuildingMesh")
        {
            BuildingMesh = Cast<UStaticMeshComponent>(StaticMeshComponent);
            UE_LOG(LogTemp, Warning, TEXT("BuildingMesh FOUND"))
            break;
        }

    }
    ensure(BuildingMesh != nullptr);

And in the **Builder, **I have declared reference to the class of the Building as follows:



    UPROPERTY(EditAnywhere, Category = "Setup")
    TSubclassOf<ASpawnBuilding> BuildingBlueprintClass;

Also, this is the way I try to get the **UStaticMesh **of the Building:


ASpawnBuilding* DefaultObject = BuildingBlueprintClass->GetDefaultObject<ASpawnBuilding>();
    const UStaticMeshComponent* MeshComp = DefaultObject->BuildingMesh;

The problem:
The Unreal Engine is crashing on that line when I start it with **“unhandled exception”

Please HELP ME :)**

That seems very long winded.

UStaticMeshComponent* StaticMeshComp = Actor->FindComponent<UStaticMeshComponent>();

then just test if its nullptr or not with

if (StaticMeshComp)
{
//Do Stuff here
}

if you are trying to get it from the CDO, then do this


if (BuildingBlueprintClass)
{
    UStaticMeshComponent* StaticMeshComp = BuildingBlueprintClass->GetDefaultObject()->FindComponent<UStaticMeshComponent>();
    if (StaticMeshComp)
    {
        UStaticMesh* StaticMesh = StaticMeshComp->StaticMesh;
    }
}

Yes, this was one of the things that I needed and the other thing is that I was executing it in the Constructor of the Builder which doesn’t have BuildingBlueprintClass initialized before the event **BeginPlay in the C++ **class. :slight_smile: I’ll go read more in-depth in **CDO **and the Blueprint and C++ execution flow to understand it better. Thank you very much for your help! :slight_smile: