Add StaticMeshComponent at runtime


I want to add a dynamic number of static mesh components to an actor at a specific event during runtime. I tried the following:

	if (System && Actor)
		TArray<AStar*> Stars = System->GetMembersByType<AStar>(AStar::StaticClass());
		for (AStar* Star : Stars)
			UStaticMeshComponent* Component = NewObject<UStaticMeshComponent>(this);
			Component->bAutoRegister = true;
			Component->SetWorldScale3D(FVector(0.1f, 0.1f, 0.1f));
			Component->SetRelativeLocation(FVector(0.f, 0.f, 10.f));

I get no error message, but nothing shows up in the world. I also tried to run it without bAutoRegister = true and without RegisterComponent() since I think they are redundant, but it nothing changed.

The variable SphereMesh is set in the Constructor like so:

static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereModelOb(TEXT("/Game/Shapes/Shape_Sphere"));
if (SphereModelOb.Succeeded())
	SphereMesh = SphereModelOb.Object;

Can you give me a hint what I am doing wrong?

Thanks in advance


I have some code that looks like this:

UMyCustomRenderingComponent* AMyActor::CreateSubComponent(...)
    UMyCustomRenderingComponent* newComponent = NewObject<UMyCustomRenderingComponent>(this);
    newComponent->AttachTo( RootComponent );
    newComponent->SetRelativeLocation( ... position ... );

    return newComponent;

which seems to work great.

Thanks for your input, but I’m afraid that this also doesn’t work for me. Just out of curiosity, is your CreateSubComponent() method inside an AActor derived class? Mine is not, do you think it makes a difference?

Yes, it is, but I don’t think that’s relevant, as long as you make the component owned by a particular Actor at some point. I think you might be missing the RegisterComponentWithWorld() call? I remember that being tricky and hard to find.

I have my own custom component which spawns a number of static mesh components and attaches to itself. I do this:

StaticMeshComponent = ConstructObject<UStaticMeshComponent>(UStaticMeshComponent::StaticClass(), GetOwner(), NAME_None, RF_Transient);

// Add to map of components.
StaticMeshComponents.Add(StaticMesh, StaticMeshComponent);
StaticMeshComponent->AttachTo(this, NAME_None, EAttachLocation::KeepRelativeOffset);

// Transform the component by transformation provided by our framework.

Which seems to be very close to what you are doing; out of curiosity, try recreating render state for them? RecreateRenderState_Concurrent etc.

I think it is relevant. Just try adding a mouse cursor in the player controller of the default top down template. You’ll find that it never shows up, but if you implement the same code in the character it works.