BP vs C++ How to Make Audio Persist Between Levels?

I am experiencing the most vexing problem. Every tutorial you see posted basically says the same thing when trying to make audio work across levels - make a custom game instance and store the audio component there. And this works… until you do it in c++

The blueprint nodes above work. I call the Test A Song event in the character blueprint, then swap the level and it persists. Perfect, now we know it works. Time to implement it into our c++ systems…

So inside of our header we go:

public:
	UFUNCTION(BlueprintCallable, Category = "Music")
	void PlaySong(USoundCue* song, float startTime = 0.0f);

private:
	UAudioComponent* AudioComponent;

And in the code file we go:

void UCustomGameInstance::PlaySong(USoundCue* song, float startTime /*= 0.0f*/)
{
    AudioComponent = UGameplayStatics::CreateSound2D(GetWorld(), song, 1.0f, 1.0f, 0.0f, nullptr, true, true);
    AudioComponent->Play(startTime);
}

This should fundamentally be the same thing, yet, when we change levels, the audio no longer persists like it’s blueprint counterpart. Am I missing something here?

UAudioComponent is not marked as a UPROPERTY macro, this can make it be garbage collected.

Also elements persisting between levels should usually be carried over in the game instance. I would probably put the audio there while travelling to another level.

Yeap, just needed to be marked with UPROPERTY(). Didn’t realize garbage collection would hit it while stored in the game instance because I imagined with the game instance persisting between levels it would also store it’s properties. Thanks.

1 Like