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()
{
	Super::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*)
		{
			continue;
		}
		if (MapName.Equals(ActorList*->GetName()))
		{
			Floor = Cast<AStaticMeshActor>(ActorList*);
			break;
		}
	}

	if (Floor)
	{
		UTextRenderComponent* Text = NewObject<UTextRenderComponent>(this);
		Text->SetRelativeLocation(FVector(-282.f, 100, 100.f));
		Text->SetTextRenderColor(FColor::Red);
		Text->SetText(FText::FromString(TEXT("Dynamically added TextRenderComponent does not work")));
		Text->SetXScale(1.f);
		Text->SetYScale(1.f);
		Text->SetWorldSize(500);

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

You need to call:



Text->RegisterComponent();


Do it after you call NewObject<>

Thx for your suggestion, but it doesn’t work.

Can anyone help me to solve this issue?

Just a guess! try shifting “UTextRenderComponent* Text” to header file.
As mentioned by TheJamsh, add “Text->RegisterComponent();” immediately after newobject.
You might need to do printf or something to check the value of floor before if(floor) statement. It might bypass the creation process.

It doesn’t work, Thx all the same :slight_smile:

You could use ATextRenderActor

Thx so much, your suggestion is very useful. I worked it out:


void ATopDownTestGameMode::BeginPlay()
{
	Super::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->GetTextRender()->SetTextRenderColor(FColor::Red);
	Text->SetActorScale3D(FVector(5.f, 5.f, 5.f));
}

2016-08-15.png

1 Like