我有一个具有HexCell类的角色,我给他添加了一个具有HexWidget类的widget组件,然后我试图获取一个链接到widget组件,但没有任何效果。我尝试了许多解决方案,但都不奏效。如何获取小组件类的引用?
class BATTLETECH_API UHexWidget : public UUserWidget
{
GENERATED_BODY()
};
class BATTLETECH_API AHexCell : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AHexCell();
UPROPERTY(VisibleAnywhere, Category="Grid Setup")
UHexWidget* Widget;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
void AHexCell::BeginPlay()
{
Super::BeginPlay();
1 // the code compiles without errors, but the engine crushed if start
Widget = Cast<UHexWidget>(GetOwner()->FindComponentByClass(UHexWidget::StaticClass()));
2 // the code compiles without errors and the scene starts, but the link remains empty
Widget = Cast<UHexWidget>(this->FindComponentByClass(UHexWidget::StaticClass()));
3 //note: see reference to function template instantiation 'T *AActor::FindComponentByClass<UHexWidget>(void) const' being compiled
Widget = GetOwner()->FindComponentByClass<UHexWidget>();
Widget = Cast<UHexWidget>(this->FindComponentByClass<UHexWidget>());
Widget = Cast<UHexWidget>(GetOwner()->FindComponentByClass<UHexWidget>());
}
这不能工作的原因有很多。
AHexCell
实例没有所有者(它是一个演员,很可能没有所有者,除非被玩家控制器拥有)。AHexCell
没有组件 UHexWidget
而且很可能永远不会有:UHexWidget是一个。UUserWidget
该类没有继承 UActorComponent
你需要做的(除了一些OOP和虚幻引擎的研究之外)是 。
class BATTLETECH_API AHexCell : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AHexCell();
UPROPERTY(VisibleAnywhere, Category="Components")
UWidgetComponent* widgetComp;
UPROPERTY(VisibleAnywhere, Category="Grid Setup")
UHexWidget* Widget;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
AHexCell::AHexCell()
{
// spawn a widget component
widgetComp = createDefaultSubObject<UWidgetComponent>("widgetComponent");
// or get it via FindComponent
// widgetComp = FindComponentByClass<UWidgetComponent>();
}
AHexCell::BeginPlay()
{
Super::BeginPlay();
// check if your pointer is valid before calling functions on it
if(widgetComp != nullptr)
Widget = Cast<UHexWidget>(widgetComp->GetUserWidgetObject());
}