Download

[SOLVED[ Getworld() from static function without pass an Object

Hi! I am slowly moving from Blueprint to C++ and I have a question:

I have a blueprint function library with a function were I give a couple float values and it returns another float result doing math with ‘time since creation’ of ‘playercontroller’

I am trying to do the same from a C++ function library but the only way I found of get world context is passing any object to the function so i can get world context of that object.

I want to do exactly the same I achieve with blueprints that means not passing any object to get the world contexts. I tried to use ‘this’ as reference but the engine dont allow because is a static function. Any help?

here is what i have working so far…i send a ‘Me’ object but i want to avoid sending any object.

float MyBPLibrary::WaveIt(AActor* Me, float TimeOffset , float Frequency, float Amplitude)
{
UObject* WorldContextObject = (UObject*)Me;
float TimeSinceCreation = WorldContextObject->GetWorld()->GetFirstPlayerController()->GetGameTimeSinceCreation();
return sin(FMath::DegreesToRadians((TimeSinceCreation+TimeOffset) * Frequency))*Amplitude;

}

Thanks!

Solution:

float MyBPLibrary::WaveIt(float TimeOffset , float Frequency, float Amplitude)
{
UWorld* world = GEngine->GameViewport->GetWorld(); // ← this is the magic line!
float TimeSinceCreation = world->GetFirstPlayerController()->GetGameTimeSinceCreation();
return sin(FMath::DegreesToRadians((TimeSinceCreation + TimeOffset) * Frequency)) * Amplitude;
}