You can create User Widgets in Pawn or Player Controller, last one is the best place.
//If you are creating it in Pawn you need the player controller
APlayerController* playercontrollertmp = Cast<APlayerController>(GetController());
// in player controller replace playercontrollertmp parameter with: this
UMyPlayerWidget* PlayerWidget = CreateWidget<UMyPlayerWidget>(playercontrollertmp, UMyPlayerWidget::StaticClass());
PlayerWidget->AddToViewport(0);
Include your custom widget class or it wont work:
// if you want to keep them in widgets folder
#include "MyProject/Widgets/MyPlayerWidget.h"
// or not
#include "MyPlayerWidget.h"
If you have compile problems check that you have the correct class which you used to create your own user widget.
It should have these:
UUserWidget
#include "Blueprint/UserWidget.h"
These are incorrect and you may get it if you use “New C++ Class” in unreal:
UUserWidgetBlueprint
#include "Blueprint/UserWidgetBlueprint.h"
Extras
You should also include these in your user widget class, they have a lot good stuff:
#include "Blueprint/WidgetBlueprintLibrary.h"
#include "Blueprint/WidgetLayoutLibrary.h"
//For example
UWidgetLayoutLibrary::ProjectWorldLocationToWidgetPosition
UWidgetBlueprintLibrary::DrawLine
One really important thing, which i see people doing (and i used to do myself) is to use GetPlayerController to get player controller class. Never use this function in Widgets because especially in multiplayer games it can return the wrong player.
APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0);
Rather use these which are designed for Widgets and are included within UseWidget class.
APlayerController* PlayerController = GetOwningPlayer();
APawn* PlayerPawn = GetOwningPlayerPawn();
//Accessing to your custom class
AMyPawn* tmp = Cast<AMyPawn>(GetOwningPlayerPawn());