无法获得到小部件组件UE4的链接

时间:2020-05-18 18:52:08

标签: c++ unreal-engine4

我有一个演员为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>());


}

1 个答案:

答案 0 :(得分:1)

由于多种原因,该方法无法正常工作:

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

除了一些OOP和虚幻引擎研究之外,您需要做的是:

UActorComponent