Preventing AudioComponent from being destroyed

Hello there!

Going straight to the problem. I’m trying to create UAudioComponent that can be paused and hold into memory until I decide to delete it. Now i have problem with it becouse after some time on level my sound just disappears.

This is how I’m creating it right now:

UAudioComponent* UAudioController::Sound2D(UObject* WorldContextObject, class USoundBase* Sound, float VolumeMultiplier, float PitchMultiplier, float StartTime)
{
	if (!Sound)
	{
		return nullptr;
	}

	UAudioComponent* AudioComponent = UGameplayStatics::CreateSound2D(WorldContextObject, Sound, VolumeMultiplier, PitchMultiplier, StartTime);
	PlaybackPositionMap.Add(AudioComponent, 0.f);
	BindDelegates(AudioComponent);
	AudioComponent->Play(StartTime);
	return AudioComponent;
}

PlaybackPositionMap is just TMap that holds reference to UAudioComponent and float that is time played from that sound.

BindDelegates function looks like this:

void UAudioController::BindDelegates(UAudioComponent* AudioComponent)
{
	if (AudioComponent->IsValidLowLevel())
	{
		AudioComponent->OnAudioPlaybackPercent.AddDynamic(this, &UAudioController::SavePlaybackPosition);
		AudioComponent->OnAudioFinished.AddDynamic(this, &UAudioController::SoundFinished);
	}
}

I do not think you need it but just to be clear with it. I tried saving reference to UAudioComponent in arrays maps static components and disallowing it’s destruction but it always dissapears. Any way I can change that?

Most likely your AudioComponent is getting picked up and destroyed by the garbage collector. I found two workarounds for this:

-Call “AddToRoot()” on your audio component, which will prevent it from getting garbage collected. Call RemoveFromRoot() when you are done with it.

-Store your reference to the component inside a UPROPERTY. If you have a UPROPERTY pointing to your AudioComponent, that should keep it from getting garbage collected.