Search code examples
c++widgetunreal-engine4game-development

How to add widget in Unreal Engine


How can I add widget to the screen in Unreal Engine? By some reason variable blackLinesWidgetClass is always null.

    FStringClassReference blackLinesWidgeClasstRef(TEXT("WidgetBlueprint'/Game/Blueprints/UI/blackLines.blackLines'"));
    UClass* blackLinesWidgetClass = blackLinesWidgeClasstRef.TryLoadClass<UUserWidget>();
    if (blackLinesWidgetClass)
    {
        UUserWidget* blackLinesWidget = CreateWidget<UUserWidget>(this->GetGameInstance(), blackLinesWidgetClass);
        if (blackLinesWidget)
            blackLinesWidget->AddToViewport();
    }

Solution

  • This worked for me

    .h

    UPROPERTY(EditAnywhere) TSubclassOf<UUserWidget> widgetBlackLines;
    UUserWidget* widgetBlackLinesInstance;
    

    .cpp

    void AAct_31::BeginPlay()
    {
        widgetBlackLinesInstance = CreateWidget<UUserWidget>(GetWorld(), widgetBlackLines);
        widgetBlackLinesInstance->AddToViewport();
    }