Download

Problems with widgets in Code

I use this tutorial https://wiki.unrealengine.com/UMG,_Referencing_UMG_Widgets_in_Code

But every time I have error:

I also have this problem with the code.
However, the program compiles without errors.


#pragma once

#include "GameFramework/PlayerController.h"
#include "CustomPlayerController.generated.h"

UCLASS()
class INDIGOPROJECT_API ACustomPlayerController : public APlayerController {
	GENERATED_BODY()

public:
	ACustomPlayerController(const class FObjectInitializer& ObjectInitializer);

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
	TSubclassOf<class UUserWidget> MainHUD;
	
protected:
	virtual void BeginPlay() override;
	class UUserWidget* MainHUDWidget;
};


#include "IProject.h"
#include "CustomPlayerController.h"
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"

ACustomPlayerController::ACustomPlayerController(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }

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

	if(MainHUD) {
		MainHUDWidget = CreateWidget<UUserWidget>(this, MainHUD);
		if(MainHUDWidget) {
			MainHUDWidget->AddToViewport();
		}
	}
}

The code error is just intellisense, it doesn’t work well with UE4. Just ignore intellisense errors.

I’m guessing you’re running this with multiple players? The player controller will exist on both the server and the associated client, but you only want to create widgets on each client.
In your BeginPlay method, wrap all the code creating the widget with if(IsLocalPlayerController()) { … }

change



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

	if(MainHUD) {
		MainHUDWidget = CreateWidget<UUserWidget>(this, MainHUD);
		if(MainHUDWidget) {
			MainHUDWidget->AddToViewport();
		}
	}
}

to



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

	if(MainHUD && **GetNetMode()!=NM_DedicatedServer**) {
		MainHUDWidget = CreateWidget<UUserWidget>(this, MainHUD);
		if(MainHUDWidget) {
			MainHUDWidget->AddToViewport();
		}
	}
}

UMG widgets or HUD only make sense on a client machine where you have a player and a screen. so if you add UMG on a server it will throw error.

What that GetNetMode()!=NM_DedicatedServer do is prevents creation of hud on a dedicated server so that hud is only created on clients or a listen server ( a listen server has a player and screen )

That won’t work. If you have a listen server, it will try to create a widget locally for every connected player since you have multiple player controllers on the server.
You need to use IsLocalPlayerController().

yeah ok deleted erronous answer

Thanks!

At the VS has tips on entering, they no longer work.
I find it difficult to work under such conditions