I've just started to learn C++ developing a game using Unreal Engine 4.26.2.
I don't really know what I'm doing.
I have created an UMG.UserWidget to show the HUD.Then I have created a C++ class that inherits from UserWidget. After that, I have reparent blueprint to that UMG.UserWidget. I've done that because I want to get access this widget from C++ code (to update players scores).
Besides that I have a C++ class, which inherits from AHUD. I use this class to show the UMG.UserWidget with this code:
Custom C++ HUD Constructor
APongHUD::APongHUD()
{
PlayerHudWidget = NewObject<UPlayerHUDWidget>(UPlayerHUDWidget::StaticClass());
ConstructorHelpers::FClassFinder<UUserWidget> WBPPlayerHudFinder(TEXT("/Game/Blueprint/Widgets/UI/UMG_PlayerHUD"));
if (WBPPlayerHudFinder.Succeeded())
{
HudClass = WBPPlayerHudFinder.Class;
}
else
{
PlayerHudWidget = nullptr;
}
}
Begin Play
void APongHUD::BeginPlay()
{
Super::BeginPlay();
if (HudClass)
{
Widget = CreateWidget<UUserWidget>(GetWorld(), HudClass);
Widget->AddToViewport();
PlayerHudWidget = Cast<UPlayerHUDWidget>(Widget);
}
}
I have tried this code with the line PlayerHudWidget = Cast<UPlayerHUDWidget>(Widget);
and commenting it with the same error.
The problem appears when I try to change the scores with this function:
void APongHUD::SetAIScored(int value)
{
if (PlayerHudWidget != nullptr)
{
PlayerHudWidget->SetAIScore(value);
}
}
At this line if (PlayerHudWidget != nullptr)
I get the error:
An exception occurred: read access violation. this was nullptr.
This is the UPlayerHUDWidget
header file:
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "PlayerHUDWidget.generated.h"
/**
*
*/
UCLASS()
class POMG_API UPlayerHUDWidget : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
class UTextBlock* Player_Score;
class UTextBlock* AI_Score;
void SetPlayerScore(int NewScore);
void SetAIScore(int NewScore);
};
And its implementation:
#include "PlayerHUDWidget.h"
#include "Components/TextBlock.h"
void UPlayerHUDWidget::SetPlayerScore(int NewScore)
{
Player_Score->SetText(FText::AsNumber(NewScore));
}
void UPlayerHUDWidget::SetAIScore(int NewScore)
{
AI_Score->SetText(FText::AsNumber(NewScore));
}
My problem is that I don't know how to update the UMG.UserWidget
HUD from C++ and what I'm trying it doesn't work.
How can I update UMG.UserWidget
HUD from C++? Maybe fixing this error.
Aucun commentaire:
Enregistrer un commentaire