我有一个 Actor BP,在这个 BP 中我有一个 UWidgetComponent,其中已经在详细信息中选择了一个 Widget 类,并且该 Widget 类有一个 TextBlock。现在,在这个 BP 中,我还有一个 C++ USceneComponent,该组件负责在每次用户按下按钮时在上面提到的 TextBlock 中显示随机文本。
这是在我的 USceneComponent 的头文件(.h)中
class UWidgetComponent* QuestionWidget;
class UQuestionProjectionText* QuestionText;
class UTextBlock* QuestionTextBlock;
然后在“.cpp”文件中,在构造函数中
QuestionWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("CodeQuestionWidget"));
QuestionTextBlock = CreateDefaultSubobject<UTextBlock>(TEXT("CodeTextBlock"));
然后在BeginPlay()中
//Gets the WidgetComponent from the BP
QuestionWidget = Cast<UWidgetComponent>(GetOwner()->GetComponentByClass(UWidgetComponent::StaticClass()));
if (QuestionWidget)
{
QuestionWidget->InitWidget();
//Gets an instance of the UMyUserWidget class, from the UWidgetComponent in the BP
QuestionText = Cast<UMyUserWidget>(QuestionWidget->GetUserWidgetObject());
this->QuestionTextBlock = QuestionText->QuestionTextBlock;
//Sets the text to an empty String
QuestionTextBlock->SetText(FText::FromString(""));
}
else
{
UE_LOG(LogTemp, Error, TEXT("QuestionWidget was not found"));
return;
}
然后在 TickComponent() 中,当用户按下按钮时,我使用看起来像这样的东西
QuestionTextBlock->SetText(FText::FromString(QuestionStringsArray[9]));
问题是,当我按下按钮时,小部件中的文本不会改变,但是如果我打印我传递的文本,它会打印字符串,所以我不会将空值传递给“ SetText()”。
另一件奇怪的事情是,BeginPlay 中设置文本的行有效,我已将其更改为随机字符串,而不是空字符串,并且它确实显示了它。
我不知道当我执行“QuestionWidget->InitWidget();”时是否会这样我正在创建一个与 BP 中的独立的新的,或者如果我只是遗漏了一些东西。如果我消除“QuestionWidget->InitWidget()”,小部件有时会按时初始化,有时则不会。
我的代码中有一些错误处理,但在这里消除了它,这样它看起来就不会太混乱。而且,没有任何错误弹出,一切都进展顺利,只是小部件没有显示更新的文本。
我正在摆弄这个,有点问题。发现我必须将文本设置为 NativeConstruct 中的某个值才能正常工作。
.h
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (BindWidget))
class UTextBlock* TB_BaseDamage;
.cpp
NativeConstruct(){
TB_BaseDamage->SetText(FText::FromString("123"));}
UpdateFunction(){
FString ToSet = FString::FromInt(MyInt);
TB_BaseDamage->SetText(FText::FromString(ToSet));}