GameInstance cast failed. Trying to make it globally available

Hello everyone.

I’m trying to make GameInstance available from any class to store some global variables in it, and so I have created some c++ code in my plugin, since GameInstance is not usually available from UObject.

I have a custom GameInstance blueprint called GlobalVariables, and it is set in the project settings to be the GameInstance to be used

.h

	UFUNCTION(BlueprintCallable, Category="test")
	static UGameInstance* GetGlobalVariables();

.cpp

UGameInstance* UMegaTestUtil::GetGlobalVariables()
{
	return ((UGameEngine*)GEngine)->GameInstance;
}

The problem I’m experiencing is that it’s failing to cast to GlobalVariables if I use the code, but not if I use the “GetGameInstance” node.

Example is executing from the PlayerController

In the below photo it works perfectly, getting “TRUE”, “VALID”, “SUCCESS”

In this one, the c++ code I wrote, it’s getting “TRUE”, “VALID”, “FAIL”

Any help is appreciated.
Thank you

Thank you for your reply!

That sounds like a plan, willing to try it out - but for some reason I can’t reparent the blueprint to it, as I can’t find it

You could instead derive from UGameInstanceSubsystem. With this you get a node available from pretty much any class.

Oh yes I forgot that It is only in C++. Allegedly they are making the Subsystem Blueprintable in later versions (4.24 4.25?) but for now it is only available in C++.

It is rather simple to add a Property in C++ to make it globally available like this though. Even a Blueprint developer should know how to do this.

That might be rated to you casting to UGameEnigne while editor use UEditorEnigne, also double check if oyu set gmae instance class correcly, check what class of object your function actully return, also on which event do you running that?

I think insed of looking to getting something from UEngine it might be easier to access UWorld insted and get UGameInstance from there. For starters there UWorld global pointer GWorld but it might not be reliable in editor considering multiple UWorld instances running in it. You can get any actor and get world from it, and from UEngine you can get PlayerController for example:

Maybe explore that in this direction