In UE5.3, I use RuntimeAudioImporter to load a wav file, which returns a USoundWave object. Due to the use of multithreading, I store it in a TQueue container. Since this container cannot be marked with UPROPERTY, it may cause the USoundWave to be released due to GC. Therefore, I called AddToRoot as soon as possible. However, I found that manually calling CollectGarbage(RF_NoFlags); still causes the USoundWave to be released. But when I stored the USoundWave in a TArray marked with UPROPERTY and called CollectGarbage(RF_NoFlags);, I found that the object was retained. Is this a bug? How can I prevent the USoundWave from being released by the GC system without marking UPROPERTY?
.h
UCLASS()
class AUDIOTEST_API AMyClass : public AActor
{
GENERATED_BODY()
...
UFUNCTION()
void OnImportFinish(URuntimeAudioImporterLibrary* importerObject, UImportedSoundWave* ImportedSoundWave, ERuntimeImportStatus Status);
TQueue<UImportedSoundWave*> Queue_Sounds;
UPROPERTY()
TArray<UImportedSoundWave*> Array_Sounds;
...
};
.cpp
void AMyClass::OnImportFinish(URuntimeAudioImporterLibrary* importerObject, UImportedSoundWave* ImportedSoundWave, ERuntimeImportStatus Status)
{
GEngine->AddOnScreenDebugMessage(-1,10,FColor::Red, __func__);
// the sound will still be garbage collected
ImportedSoundWave->AddToRoot();
Queue_Sounds.Enqueue(ImportedSoundWave);
// no garbage collected
Array_Sounds.Add(ImportedSoundWave);
}