UnPure GameInstance Casting ? C++

Hi, How to cast, I mean to get a reference of the class MyGameInstance?

this is how I cast to my gamestate:

if (AMyGameState* GS = GetWorld()->GetGameState<AMyGameState>())
{
  GS->DoSomething();
}

i want something same to cast to mygameinstance…

is this coorect?

UMyGameInstance * MyGameInstance_Ref;
UGameInstance* GameInstanceRef = UGameplayStatics::GetGameInstance(this);
MyGameInstance_Ref= Cast<UMyGameInstance >(GameInstanceRef );
if(MyGameInstance_Ref)
{
  GameInstanceRef->DoSomething();
}

UWorld::GetGameInstance

1 Like

GetWorld()->GetGameInstance();

Look into the GameplayStatics.cpp to see what the function does, I’ve told it to you several times already. It takes you just 10 seconds instead of posting here and waiting for an answer for several hours.

2 Likes

for example like this? UMyGameInstance * MyGameInstanceRef = GetWorld()->GetGameInstance<UMyGameInstance >();

and I can use MyGameInstanceRef to access the MyGameInstance members?

1 Like

By the way, what do you actually need a custom game instance for? (Its use cases are somewhat uncommon.)

I have some member functions in game instance and want to access them.

just doing UMyGameInstance * MyGameInstanceRef; returns null pointer

This returns a null pointer.

UMyGameInstance * GS = GetWorld()->GetGameInstance<UMyGameInstance>();

image_2022-08-30_061151455

IDK what this syntax GetGameInstance<UMyGameInstance>(), is it an old-style cast of some sort?

  1. Make sure GetWorld() return something. It can only work when game has started, so no constructor or OnConstruction;
  2. Make sure GetGameInstance() returns something.
  3. Only then Cast<UMyGameInstance>(GetGameInstance()) to see if it casts right.

If p.1-2 work but p.3 does not, maybe you haven’t selected your custom game instance in the project settings?..

1 Like

It’s called a member function template call:

template< class T >
T* GetGameInstance() const 
{ 
	return Cast<T>(GetGameInstance()); 
}
1 Like

Where are you calling this function from?

Why did you put the member functions in game instance and not in another class like game mode or another kind of actor or uobject? What do the functions do?

the function is returning some default random values

Ah, I see, thank you.

1 Like

Hi Alexa,
when you create your game instance you have to make sure that in your project settings, you set the project game instance to the one you just created that way you don’t get a null value each time you call the get game instance.
by default, this will be what your project settings will look like

1 Like