规避生命周期加载顺序问题

发布于 2024-04-19  35 次阅读


有的组件可能在一个tick里先后加载,例如在Beginplay里需要调用Owner的另一个组件时,可能因为还没加载好就拿不到,咋办?

使用定时器

如下代码所示,直接在下一个tick跑逻辑

void UOdyAIPerceptionComponent::BeginPlay()
{
	Super::BeginPlay();
	GetWorld()->GetTimerManager().SetTimerForNextTick([this]
	{
            if (!IsValid(AIOwner))
            {
                return;
            }
	});
}

依靠生命周期

直接在生命周期的后一个阶段做逻辑

AActor:

https://www.brightdevelopers.com/unreal-engine-4-game-flow-actor-lifecycle-overview

UActorComponent:

  • UActorComponent::OnComponentCreated
  • UActorComponent::OnRegister
  • UActorComponent::InitializeComponent
  • UActorComponent::BeginPlay
  • UActorComponent::TickComponent
  • UActorComponent::EndPlay
  • UActorComponent::UninitializeComponent
  • UActorComponent::OnUnregister
  • UActorComponent::OnComponentDestroyed