In this lesson, you will learn how to create custom BTService nodes to perform efficient, periodic updates to your Blackboard data, ensuring your AI makes decisions based on fresh information.
The Role of AI Services
While Tasks perform actions (like moving or playing an animation), Services perform background calculations. A Service runs periodically as long as its branch in the Behavior Tree is active. Instead of running expensive logic in every frame or relying on cumbersome events, Services allow you to "poll" the world state and update Blackboard keys at a set frequency.
Implementing a Distance Checker
A classic use case for a Service is calculating the distance between an AI and its target. By placing this in a Service, the AI constantly knows if it is within range to attack, without needing to clutter your Behavior Tree Tasks with math logic.
When you create a custom BTService, you override the ReceiveTickAI function. Here is how that looks in logic:
// Inside your custom BTService_UpdateDistance.cpp
void UBTService_UpdateDistance::TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);
AAIController* AICon = OwnerComp.GetAIOwner();
UBlackboardComponent* BBComp = OwnerComp.GetBlackboardComponent();
if (AICon && BBComp)
{
AActor* Target = Cast<AActor>(BBComp->GetValueAsObject(TargetKey.SelectedKeyName));
if (Target)
{
float Distance = FVector::Dist(AICon->GetPawn()->GetActorLocation(), Target->GetActorLocation());
BBComp->SetValueAsFloat(DistanceKey.SelectedKeyName, Distance);
}
}
}
Efficiency Through Intervals
The beauty of the BTService lies in its Interval and Random Deviation settings. You do not need to calculate distance 60 times per second. By setting the Interval to 0.5 seconds, the Service updates your Blackboard only twice per second. This keeps your performance overhead low while maintaining high-fidelity AI awareness.
Because this is a "Tickable" system managed by the Behavior Tree, the Service will automatically stop executing the moment the AI exits that specific branch of the tree, ensuring that logic only runs when it is actually needed.
Key Takeaway: Use BT Services to handle background Blackboard updates at controlled intervals, preventing performance-heavy logic from bloating your active Tasks.