How to get my gamemode in a C++ function library?

AmyGamemodeCPP not UMyBlueprintFunctionLibrary.

UCLASS()
class BLOCKARDS_API AmyGamemodeCPP : public AGameModeBase
{
	GENERATED_BODY()

public:

	AmyGamemodeCPP();
.
.
.
.

Maybe try and check if UWorld* you’re getting is even valid?

AmyGamemodeCPP* UMyBlueprintFunctionLibrary::myGamemode()
{
    if (GEditor->GetEditorWorldContext().World() == nullptr)
    {
        GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, "Get World FAILED");
        return nullptr;
    }
    return Cast<AmyGamemodeCPP> (   GEditor->GetEditorWorldContext().World()->GetAuthGameMode());
}

image

image

AmyGamemodeCPP* UMyBlueprintFunctionLibrary::myGamemode()
{

	if (GEditor->GetEditorWorldContext().World() == nullptr)
	{
		GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, "Get World FAILED");
		return nullptr;
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, "Get World is OK!");
	}
	return Cast<AmyGamemodeCPP> (   UGameplayStatics::GetGameMode(GEditor->GetEditorWorldContext().World()));
}

sigh…

It seems world->GetAuthGameMode() is only valid at runtime. So your kind of functionnality should not run in editor I guess…

Okay, okay, it’s a step-by-step process =)
Now check if GetAuthGameMode() is not nullprt, before casting =)

if (GEditor->GetEditorWorldContext().World()->GetAuthGameMode() == nullptr)
{
GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, “Game Mode NULL”);
}

Is this game mode is fine, then you have to look into your custom game mode.

No, GetAuthGameMode() works in editor just fine, I use it all the time.

image

GetAuthGameMode is null

When I’m a running from editotool widget button click in editor, it’s also null.

Maybe the problem is that my actual gamemode in the editor is a child (subclass?) of my GamemodeCPP??? anyway even being a blueprint gamemode, as being child of GamemodeCPP should cast ok.

Well, that’s why I ended up just using Cast<AMyGameMode>(GetWorld()->GetAuthGameMode()) in the actors without libraries; I get it when a function is complex, but you’ll still have one line of code to get the game mode, either by invoking a function library, or getting game mode directly. In any case, you don’t want to get game mode multiple times if you use it a lot; just get a reference to it on BeginPlay() and use this reference throughout the code.
That’s my approach =)

2 Likes

Yeah…you’re right…my approach is handy in the blueprint world with blueprint functions…just wanted to move the function library to C++ but actually is not needed. I can keep using my blueprint library for blueprints and simple code for C++ instead trying to make the same. I was overthinking with no reason :slight_smile:
@Tuerer and @matrem84 THANKS A LOT for your time and advice!

Best,
Dany