组件启用 Tick
在这一篇文章中,我们继续完善 Box 组件,我们使其启用 Tick。
我们主要还是参考场景组件的默认代码。如代码清单 1 所示,我们复制 TickComponent() 函数的定义。
- UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
 - class CRYPTRAIDER_API UTriggerComponent : public UBoxComponent
 - {
 - GENERATED_BODY()
 - public:
 - // Called every frame
 - virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
 - };
 
接着,如代码清单 2 所示,我们复制 TickComponent() 函数的实现,并加了日志打印确认。注意不要忘记复制父类的 TickComponent() 调用。
此处的 Super 是 Unreal Engine 生成的类型定义,定义在 GENERATED_BODY() 宏里。
比如此处,UTriggerComponent 继承于 UBoxComponent。Super 的定义为:typedef UBoxComponent Super。
- // Called every frame
 - void UTriggerComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
 - {
 - Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
 - UE_LOG(LogTemp, Display, TEXT("Trigger Component Is Ticking"));
 - }
 
代码实现好之后,我们运行程序,会发现并没有打印我们在 TickComponent() 中添加的日志。
这是因为,Actor 的 Tick 才是默认启用的。而 Unreal Engine 出于性能考虑,组件的 Tick 默认是不启用的。
开启的方式我们还是参照场景组件的代码。如代码清单 3 所示,我们添加 UTriggerComponent 的构造函数,其中设置 PrimaryComponentTick.bCanEverTick 变量为 true。
- // Sets default values for this component's properties
 - UTriggerComponent::UTriggerComponent()
 - {
 - // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
 - // off to improve performance if you don't need them.
 - PrimaryComponentTick.bCanEverTick = true;
 - UE_LOG(LogTemp, Display, TEXT("Construct"));
 - }
 
注意,构造函数的添加,即时编译大概率会生效不了。要退出整个编辑器,重新编译 C++ 工程。
启动组件 Tick 之后,运行程序,如图 1 所示,可以看到控制台中打印了添加的日志。