Ways to get GameInstance in Unreal Engine C++

Feb, 17 2021— #basic

There are several ways to get the GameInstance, and for the most part it depends on where you want to get this object from.

In the examples below, "UGameInstanceCreated" is a C ++ generated GameInstance class.

If you have UWorld:

UGameInstanceCreated* GameInstanceRef = Cast<UGameInstanceCreated>(UGameplayStatics::GetGameInstance(GetWorld())

If you don't have UWorld:

UGameInstanceCreated* GameInstanceRef = Cast<UGameInstanceCreated>(GEngine->GetWorld()->GetGameInstance());

If you are unsure of a specific method, there is an option for testing to understand that at least one of the ways to get GameInstance works:

if (GetWorld() != nullptr && GetWorld()->GetGameInstance() != nullptr)
{
	UGameInstanceCreated* GameInstanceRef = Cast<UGameInstanceCreated>(UGameplayStatics::GetGameInstance(GetWorld())
}
else if (GetGameInstance())
{
	UGameInstanceCreated* GameInstanceRef = Cast<UGameInstanceCreated>(GEngine->GetWorld()->GetGameInstance());
}else
{
	UE_LOG(LogTemp, Error, TEXT("Game Instance cannot be obtained") );
}
By Georgy Treshchev

Unreal Engine Developer. Contact for any questions. Telegram chat, e-mail, Github.