暴露 C++ 组件

在上一篇文章中,我们已经了解了如何使用 UPROPERTY() 暴露 C++ 组件,有各种限定词。

在这一篇文章中,我们将之前的 C++ 组件暴露给蓝图。然后在蓝图里,按照图 1 的结构,在蓝图里设置和组装 Mesh。

图1 结构

如代码清单 1 所示,我们对各个组件变量添加 UPROPERTY 属性,设置为可见的、蓝图只读的。

注意要添加 meta = (AllowPrivateAccess = "true")。

因为此处变量是私有的。不加的话,编译会报“BlueprintReadOnly should not be used on private members”的错误。

代码清单 1 暴露变量
  1. UCLASS()
  2. class TOONTANKS_API ABasePawn : public APawn
  3. {
  4.     GENERATED_BODY()
  5.  
  6. private:
  7.     UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
  8.     UCapsuleComponent* CapsuleComp;
  9.  
  10.     UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
  11.     UStaticMeshComponent* BaseMesh;
  12.  
  13.     UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
  14.     UStaticMeshComponent* TurretMesh;
  15.  
  16.     UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
  17.     USceneComponent* ProjectileSpawnPoint;
  18. };

接着回到坦克和炮塔的蓝图中,如图 2 所示,在左侧的组件窗体中可以看到暴露出来的 C++ 变量。我们在 静态网格体 属性里设置底座和炮塔 Mesh。然后调整碰撞胶囊体的大小和发射点的位置。

图2 设置 Mesh

坦克和炮塔蓝图设置好之后,如图 3 所示,我们就可以把它们摆放到场景中。

图3 场景