Implementing Communication via Direct References
In this lesson, you will learn how to create a "direct line" of communication between two objects so they can trigger immediate state changes in each other without relying on complex messaging systems.
The Core Concept
Sometimes, your gameplay logic is simple: a Button actor needs to turn off a Light actor, or a PlayerCharacter needs to tell an InventoryComponent to add an item. Instead of using broad systems like Event Dispatchers or Interfaces, we use Direct References.
A direct reference is essentially a variable that stores a pointer to a specific actor or component currently living in your world. By holding this reference, your object can directly access the public functions or variables of the target. It is the most performant and straightforward way to bridge two objects.
Implementation Illustration
Imagine you have an AInteractableButton that needs to toggle a specific APointLight. You define a variable in your button class to hold a reference to that light:
// Inside AInteractableButton.h
UPROPERTY(EditAnywhere, Category = "Interaction")
class APointLight* TargetLight;
// Inside AInteractableButton.cpp
void AInteractableButton::OnInteract()
{
if (TargetLight)
{
// We communicate directly with the pointer
TargetLight->ToggleVisibility();
}
}
In the Editor, you simply drag your light into the TargetLight slot in the details panel of your button. Now, the button has a direct "address" for the light. When the player interacts with the button, it sends a command exactly where it needs to go.
Why Direct References?
Direct references are perfect for one-to-one relationships where the relationship is known at design time. Because you aren't broadcasting to the entire game world, the engine doesn't have to search for listeners—it simply executes the function on the pointer you provided. It is fast, easy to debug, and maintains a clear, explicit connection between your gameplay objects.
Just remember: keep your references valid. If an object is destroyed during gameplay, always check that your pointer isn't nullptr before trying to use it to avoid crashes!
Key Takeaway: Direct References provide a high-performance, explicit link between objects, allowing you to trigger logic directly by storing and invoking pointers to specific actors or components.