核心是用 C++ 基类封装逻辑,蓝图派生类负责布局 / 样式,彻底解耦。
原来的umg

改后
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "PlayerHPBarWidget.generated.h"
class UProgressBar;
UCLASS()
class ROUGHLIKE1_API UPlayerHPBarWidget : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(meta = (BindWidget))
UProgressBar* P_HP;
UFUNCTION(BlueprintCallable, Category = "UI")
void UpdateHeadBar(float curHP, float maxHP);
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "umg/PlayerHPBarWidget.h"
#include <Components/ProgressBar.h>
void UPlayerHPBarWidget::UpdateHeadBar(float curHP, float maxHP)
{
if (!P_HP)
{
return;
}
if (maxHP <= 0.0f)
{
return;
}
if (curHP <= 0.0f)
{
return;
}
float percent = curHP / maxHP;
percent = FMath::Clamp(percent, 0.0f, 1.0f);
P_HP->SetPercent(percent);
}
