Wait for widget creation for another class?

I am creating a widget in c++ within the BeginPlay function. Another script wants to access this widget. It wants to access within a BeginPlay function. So its looks like this:

HudClass

void ARTSMainHud::BeginPlay()
{
	Super::BeginPlay();

	if (hudWidgetClass)
	{
		UUserWidget *hudMainWidget = CreateWidget<UUserWidget>(this->GetOwningPlayerController(), this->hudWidgetClass);
		hudMainWidget->AddToViewport();
	}
}

CameraPawn

void ARTSCameraPawn::BeginPlay()
{
	Super::BeginPlay();
	
	// Bind to the mouse move events
	ARTSMainHud *mainHud = Cast<ARTSMainHud>(GetWorld()->GetFirstPlayerController()->GetHUD());

	if (mainHud)
	{
		URTSMainWidget *mainWidget = Cast<URTSMainWidget>(mainHud->hudMainWidget);
	if (mainWidget)
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, "Called");
		if (mainWidget)
		{
			mainWidget->OnMouseMoveRight.AddDynamic(this, &ARTSCameraPawn::mouseScrollRight);
		}
	}
	}
}

So the cast to the mainHud works but the cast to URTSMainWidget doesn’t work’s. And I think it’s because the widget wasn’t created yet. But how I can wait for it to be created?

I also want to cast as early is possible because as you can see I want to add a function to the delegate within the hudMainWidget.

I think you are right, it doesn’t work because both may happen simulatenously or in whatever order the engine decides. You basically have to find a way to tie the one thing to the other.

One way to do this is to have one thing spawn/create the other. I don’t know your game, so you have to decide on your own if that makes sense in your case, but I think there is nothing speaking against having the pawn create the widget (since it manipulates the pawn it should sort of belong to it in my opinion).

Another solution would be to move the code that is currently in the CameraPawn into the Hud Class. To still have a reference to your pawn you could use GetWorld()->GetFirstPlayerController()->GetPawn(); and then cast it to your pawn class. (Only works if your pawn is possesed by the player).

The very last resort would be to move the CameraPawn code into its tick function, and check if the widget is created yet every frame. This would be a quick and abominably dirty solution :smiley:

I would prefer the first solution, since it seems to me that the ui should belong to the pawn anyway.

Oh yeah the first solution sounds great. I though I have to create it within my DefaultHud class because I am assigning it as default hud. Anyways it worked like a charm!