Understanding the WorldContextObject
In an Actor class, you can get a World (current level) reference using the GetWorld() function.
However, static functions must receive an UObject as a parameter in order to call its GetWorld() function and obtain the World reference. This parameter is known as WorldContextObject.
There is a specifier of type Metadata called WorldContext that is used to automatically fill in the parameter WorldContextObject when it is called in Blueprint. That way, the WorldContextObject parameter is not even displayed in the Blueprint node.
The code below shows an example of using the WorldContext specifier in the declaration of the GetPlayerPawn() function of the UGameplayStatics class:
UFUNCTION(BlueprintPure, Category="Game", meta=(WorldContext="WorldContextObject", UnsafeDuringActorConstruction="true")) static class APawn* GetPlayerPawn(const UObject* WorldContextObject, int32 PlayerIndex);
Note that the Blueprint node of GetPlayerPawn() does not display the WorldContextObject parameter:
You must provide a WorldContextObject if you call GetPlayerPawn() in C++. If it is being called from an Actor class, you can pass the this pointer or to make it clearer you can pass the return of the GetWorld() function as shown in this example:
APawn* PlayerPawn = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
Now that we know what static functions are and understand the use of WorldContextObject, we are ready to create our own Blueprint Function Library in the next article.