c++ - 无法获取到小部件组件 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>());
}
解决方案
由于多种原因,这不起作用:
AHexCell
实例没有所有者(它是一个演员,它很可能没有所有者,除非被玩家控制器拥有)。AHexCell
没有组件UHexWidget
并且可能永远不会有:UHexWidget 是一个UUserWidget
类不继承的UActorComponent
- 这是错误的,因为 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());
}
推荐阅读
- android - 在带有 GridLayoutManager 的 RecyclerView 中,可扩展项目在缩小后仍占用额外空间
- javascript - 如何显示从 msal graph API 收到的二进制帐户图像?
- javascript - Import * as firebase from 'firebase/app' 返回 undefined
- javascript - 将 InDesign 表格导出到 Excel
- javascript - 阻止来源为“myMainPage.com”的框架访问跨域框架
- python - 更改 pyinstaller 可执行文件的 Stanza 模型目录
- javascript - 在 Leaflet 网页上发出 WMS 请求时定义 TileSize
- bash - 使用 bash 脚本中的循环解压缩目录中的所有文件
- c++ - Clang 格式错误的枚举大括号并忽略设置
- angular - Angular 2 - scrollPositionRestoration:“启用”不适用于每个组件