首页 > 解决方案 > 无法获取到小部件组件 UE4 的链接

问题描述

我有一个 HexCell 类的演员,我向他添加了一个 HexWidget 类的小部件组件,然后我尝试获取到小部件组件的链接,但没有任何效果。我尝试了很多解决方案,但没有任何效果。如何获取小部件类的参考?

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>());


}

标签: c++unreal-engine4

解决方案


由于多种原因,这不起作用:

  1. AHexCell实例没有所有者(它是一个演员,它很可能没有所有者,除非被玩家控制器拥有)。
  2. AHexCell没有组件UHexWidget并且可能永远不会有:UHexWidget 是一个UUserWidget类不继承的UActorComponent
  3. 这是错误的,因为 1) 和 2)

您需要做的(除了一些 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());
}

推荐阅读