Add component to blueprint in editor

I have a custom button in the blueprint editor that I am trying to use to add components to a custom actor class blueprint.

The button fires off a function in the actor class .cpp:

    UStaticMeshComponent* MyMesh = NewObject<UStaticMeshComponent>();

When I run it, it gets to the RegisterComponent and breaks at

AActor* MyOwner = GetOwner();

When GetOwner() returns NULL inside the RegisterComponent call.

Anyone know a solution to this or a better way to add components through c++ inside the blueprint editor?

Thanks in advance!

Would you mind trying this:

UStaticMeshComponent* MyMesh = ConstructObject<UStaticMeshComponent>(UStaticMeshComponent::StaticClass(), this);

Hey eXi,

Thanks for the reply! I tried that code but now I get this error:

Cast of Package /Engine/Transient to Level failed

I am guessing I am having problems because I am trying to create components in the editor as opposed to at runtime…but would think there should be some way to do it…

The code above is something i used to create SplineMeshs in the OnConstruction Function. I was sure i created a UStaticMeshComponent with this too. Does your BP have any other Root components before you create the ones on runtime? This error can have multiple sources.

Using ContructSubobject for a NON Component, not initializing your Arrays and so on.

I guess the game runs fine without that line above or? I would really make sure that you have a root component set before adding components to it. For example a simple SceneComponent in the contructor.

I do have a SceneComponent created in the constructor of the blueprint class:

USceneComponent* MyScene = ObjectInitializer.CreateDefaultSubobject(this, TEXT(“Root”));
RootComponent = MyScene;

I am actually not trying to run this code in a game though…just in the editor. I am trying to extend the editor and have a button to add components to the blueprint in the blueprint editor.

So basically my procedure to test this code is I open Unreal and create a new blueprint class using my Actor class. Then in the File menu of the blueprint editor I have a menu button that runs the code in my first post to create a StaticMeshComponent. But I can’t seem to get it to work…