Add Replicated Components in Runtime Problem

Hi Guys!

I am trying to add components to my replicated actor. First I’ve added a replicated scene as a RootComponent. It worked fine. I’ve seen this scene on the client also, but when I am trying to create a new mesh component, attach it to this scene and set it as replicated, I get an error in logs and then client restarts. This is my error:
LogNetTraffic:Error: ReadContentBlockHeader: Stably named sub-object not found. Actor: GameGeneratedActor_7
LogNet:Error: UActorChannel::ReceivedBunch: ReadContentBlockHeader FAILED. Bunch.IsError() == TRUE. Closing connection.

Here is my code for creating an actor (I just simply place this actor on the map):


AGameGeneratedActor::AGameGeneratedActor(const class FObjectInitializer& PCIP)
: Super(PCIP), objectInitializer(PCIP)
{
	if (Role < ROLE_Authority){
		UE_LOG(GamoraLog, Warning, TEXT("CLIENT : CREATING AN OBJECT"));
	}
	else {
		UE_LOG(GamoraLog, Warning, TEXT("SERVER : CREATING AN OBJECT"));
	}
	RootComponent = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("DefaultScene"));
	RootComponent->OnComponentCreated();
	RootComponent->RegisterComponent();
	RootComponent->SetIsReplicated(true);
	bNetLoadOnClient = false;
	bReplicates = true;
}

In another function, which I call from the server to create a new component:


		class UMeshComponent* meshC = objectInitializer.CreateDefaultSubobject<UMeshComponent>(this, TEXT("SomeMesh"));
		meshC->AttachTo(RootComponent);
		meshC->OnComponentCreated();
		meshC->RegisterComponent();
		meshC->SetIsReplicated(true);

Note: When I move the code for component creation to the constructor, it works.

Can you help me, what am I doing wrong, and how can I create components in runtime with replication?

I had the same problem , I couldn’t still find a solution. (Unreal engine 4.16)

You need to use NewObject to create components at runtime, you can’t store the Object Initializer to create objects (it’s a reference anyway, so you can’t even guarantee it exists)



UMyComponent* NewComponent = NewObject<UMyComponent>(PointerToActor, MyComponent::StaticClass());
NewComponent ->RegisterComponent();
// Now you can do stuff
// The component will replicate if it has SetIsReplicated(true) in it's constructor.


I create weapons, inventory etc. this way and have done for yonks. Replication works as normal!