How to create Text Render at runtime in C++

I want to create a Text Render Component and attach it to floor at runtime.
following is my test code, but it doesn’t work:

void ATopDownTestGameMode::BeginPlay()

	const TArray<AActor*> ActorList = GetWorld()->GetLevel(0)->Actors;
	const FString MapName("Floor");
	AStaticMeshActor* Floor = NULL;
	for (int i = 0, size = ActorList.Num(); i < size; i++)
		if (!ActorList[i])
		if (MapName.Equals(ActorList[i]->GetName()))
			Floor = Cast<AStaticMeshActor>(ActorList[i]);

	if (Floor)
		UTextRenderComponent* Text = NewObject<UTextRenderComponent>(this);
		Text->SetRelativeLocation(FVector(-282.f, 100, 100.f));
		Text->SetText(FText::FromString(TEXT("Dynamically added TextRenderComponent does not work")));

		Text->AttachToComponent(Cast<USceneComponent>(Floor), FAttachmentTransformRules::KeepRelativeTransform);

I believe text components need initialization so if you use “CreateDefaultSubObject” function then it should work, but it can be used only inside constructor function, with FObjectInitializer object.

I worked it out:

void ATopDownTestGameMode::BeginPlay()

	Text = GetWorld()->SpawnActor<ATextRenderActor>(ATextRenderActor::StaticClass(), FVector(0.f, 100, 170.f), FRotator(90.f, 180.f, 0.f));
	Text->GetTextRender()->SetText(FText::FromString(TEXT("Dynamic Text")));
	Text->SetActorScale3D(FVector(5.f, 5.f, 5.f));


1 Like

It sorted out. Thx all the same :slight_smile:

Can you help me with this ?
I’m having the error “ATextRenderActor is not a class or namespace name” when using your code.

You can add header ‘Runtime/Engine/Classes/Engine/TextRenderActor.h’ and try again.

For anyone else who happens upon this answer. Here is how to attach Text in the constructor to a specific socket on a static mesh:

UTextRenderComponent* _text; // define this in your .h file

// in your object constructor create the text object
_text = CreateDefaultSubobject<UTextRenderComponent>("TextComponent");
_text->SetText("Some Text");
_text->AttachTo(_rootComponent, "SocketName");