How to pass actor component to game instance properly?

Hi,
Does anyone have an idea how to properly pass actor component variable to game instance and back so that I won’t get nullptr?

This is how I declare actor component variable in the first place in my Character class header, and as long as I don’t have to transition between levels it works quite fine:

	UPROPERTY()
		UEQHolder* playerEquipment;

And declaration in game instance subclass looks identically:

	UPROPERTY()
		UEQHolder* playerEquipment;

This is how I save it to game instance:

	UDataKeeper* game = Cast<UDataKeeper>(GetGameInstance());
	game->playerEquipment = playerEquipment;

However when I load it in my Character class BeginPlay, it returns nullptr:

UDataKeeper* game = Cast<UDataKeeper>(GetGameInstance());
	if (game != nullptr)
	{
		if (game->wasInitialized)
		{
			playerEquipment = game->playerEquipment;
			if (playerEquipment == nullptr)
			{
				UE_LOG(LogTemp, Warning, TEXT("Player equipment is nullptr!"));
			}
		}
	}
	else
	{
		UE_LOG(LogTemp, Error, TEXT("Game instance returned nullptr!"));
	}

LogTemp: Warning: Player equipment is nullptr!

Just to be sure, I added checking if that pointer is null already at Saving to instance and it is indeed:

	game->playerEquipment = playerEquipment;
	if (game->playerEquipment == nullptr)
	{
		UE_LOG(LogTemp, Error, TEXT("Player equipment in saving to instance is nullptr!"));
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("Player equipment in saving to instance is not null!"));
	}

LogTemp: Error: Player equipment in saving to instance is nullptr!

Any ideas what am I doing wrong?

Wait, I’m confused. In the last paragraph you say that the reference is NULL as soon as you set it. But in the beginning you say it works fine unless you load another level. So which is it?

Sorry, this indeed is unclear. It works as long as I don’t pass to game instance and use only in my Character class

If you are trying to preserve your ActorComponent between levels by referencing it in the GameInstance, then well, that’s not going to work. The world gets destroyed on level transitions, and your ActorComponent with it. If you want to preserve data that’s stored in the ActorComponent, I recommend you put that all in a struct. Then you can just copy the structure into the GameInstance and you data will live on.

Also, please don’t think of the GameInstance as a “DataKeeper.” This is a common misconception I hear a lot. Think of your GameInstance as the single object that IS your game. The GameInstance is what creates the GameMode. So it’s not just a convenient object for storing data.

Hope this helps!