How to make such a cast in c++

how to make such a cast in c++

Hi,
there are few casting methods in c++ like Cast<>, static_cast<>, dynamic_cast<> etc …

Here’s an example of casting the GameMode:

So I have created a GameMode that inherits from the class AGameModeBase (normally all game modes inherit from that class). And now I have my Actor searching for game mode and casting it to my new Game Mode :

	AMyNew_GameModeBase* MyNewGameModeBase = Cast<AMyNew_GameModeBase>(()->GetAuthGameMode());
AMyNew_GameModeBase* MyNewGameModeBase = static_cast<AMyNew_GameModeBase*>(()->GetAuthGameMode());
AMyNew_GameModeBase* MyNewGameModeBase = dynamic_cast<AMyNew_GameModeBase*>(()->GetAuthGameMode());
AMyNew_GameModeBase* MyNewGameModeBase = (AMyNew_GameModeBase*)()->GetAuthGameMode();

then we can check if the cast was a success or not :

if (IsValid(MyNewGameModeBase))
	{
		UE_LOG(LogTemp, Warning, TEXT("MyGameMode type: %s"), *MyNewGameModeBase->GetClass()->GetName());
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("Cannot cast the game mode :( "));

	}

those are examples of casting methods for different uses, and for your case, it’s just for simple case I encourage you to use the Cast<>, the first method above.
Hope this helps :slight_smile:

Hi Senuareborn

Casting in Blueprint is different to how casting works in C++. You cast objects in C++ the same way as you would cast any data in C++. Note you will need to ensure your objects you are casting to has a C++ base as you cannot cast directly to Blueprint (well technically you can, but its not advised and you certainly will not be able to access any internal members).

This is an example on how to do that function in C++

.h 
UFUNCTION(BlueprintPure, Category = "Support Functions")
ATestGamemode* GetGamemode(); 

.cpp
ATestGamemode* ATestActor::GetGamemode()
{
	return Cast<ATestGamemode> ( UGameplayStatics::GetGameMode( GEngine->() ) );
}

Note you need to include: #include “Kismet/GameplayStatics.h” in order to access the GetGamemode() function.

Hope this helps.

Alex

Just note that Cast<> is a UE4 thing, not standard C++ casting method. The big difference is it checks in UE4 reflection system that object you try to cast is actually related to class you try to cast to. If it fails it returns nullptr (you don’t need to do IsValid at that point to check, just normal null pointer check is enough and faster).

Thanks **** for your comment and for the explanations about Cast :slight_smile:

Thanks guys