How to get a reference to my GameMode class instance

Hi All,

I’ve searched the web and the source code but can’t figure it out.
I am trying to call a function in my GameMode class from my Character.

Thanks.

()->GetAuthGameMode()

It will return AGameMode pointer so you will need to cast it to your gamemode class pointer fi you want to call your code in it

(ASomeGameMode*)()->GetAuthGameMode()

Ah thanks very much! I found the solution just as this notification rolled in :/.

I just have another quick question:

When casting to e.g. “MyAwesomeGameMode”, is the only way to get the compiler to recognize this class to include it in the class I’m trying to do the cast in?

i.e. by adding
#include “MyAwesomeGameMode.h”

I believe there is a typo in your 2nd code line. World should be .

ASomeGameMode* gm = (ASomeGameMode*)()->GetAuthGameMode();

You can add the header inclusion in you PCH file, that one you have to include it anyway at the start of your cpp or your project won’t compile. Other than that if you declare your game mode member pointer of your class you can simply forward declare it. class MyGameMode; before your class declaration where you want to store the pointer to your game mode. Once in the cpp you must have an include of your game mode header somewhere though, be it a direct include or via PCH.

indeed there is

Note that GameMode is a Server only object. It will return NULL in a network game on the clients.

maybe

if(()) {
  auto gamemode = (ASomeGameMode*)()->GetAuthGameMode();
}

is the better choice, because it stops the editor from crashing. (if you put it into the constructor at least)

Is it possible that calling the function GetAuthGameMode inside the constructor of the actor crashes the editor? Because that’s what is happening. I can call the function in BeginPlay, but not in the constructor. Is that normal?

Yups, Its normal. When we call the GetAuthGameMode function, it returns the pointer to actual object. In construction phase, the object is not present. (A kind of NULL). That is why editor crashes.
But in the BeginPlay function, all of the construction phase is completed and the GameMode object now actually exists. Hence, no editor crashes

Also you could use short template way

()->GetAuthGameMode<ASomeGameMode>()

its better to use Cast<>() too its ;p its old post before i knew about it and those templates been made

What if you want to know the class name of your gamemode without casting? I mean what if you have a lot of gamemodes and dont want to cast one by one. just know wich class is it?

There are many built-in functions belonging to UObject to assist with this, e.g.

  • SomeGameModeInstance->GetClass()->GetName()
  • SomeGameModeInstance->GetClass()->GetFName()

See https://answers.unrealengine.com/questions/350488/how-to-get-c-class-name-of-object.html