Correct way to create mediaplayer in 4.19

I’m converting my project from 4.18. I have UMediaPlayer* MediaPlayer; in header and this in BegingPlay():

MediaPlayer = NewObject<UMediaPlayer>();
			NewMediaSoundComponent = NewObject<UMediaSoundComponent>(this);
			NewMediaSoundComponent->SetMediaPlayer(MediaPlayer);
			//NewMediaSoundComponent->MediaPlayer = MediaPlayer;
			NewMediaSoundComponent->bAllowSpatialization = 0;
			NewMediaSoundComponent->bIsUISound = true;
			NewMediaSoundComponent->SetActive(true);
			NewMediaSoundComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
			NewMediaSoundComponent->UpdatePlayer();

			MediaPlayer->PlayOnOpen = false;
			MediaPlayer->OnMediaOpened.Add(mediaOpenedDelegate);
			MediaPlayer->OnMediaOpenFailed.Add(mediaOpenedDelegate);
			MediaPlayer->OnMediaClosed.Add(mediaClosedDel);
			MediaPlayer->OnEndReached.Add(endReachedDel);
			MediaPlayer->OnPlaybackResumed.Add(playbackResumedDel);

One thing I noticed right away was you need to SetMediaPlayer instead of assigning the variable. I left the old code commented out and is only thing I changed. However I’m getting an access violation error when trying to do anything on the MediaPlayer object now. For instance if I do this:

MediaPlayer->Close();

It will crash with access violation error.

Make sure you assign NewMediaSoundComponent and MediaPlayer to some other Actor’s or UObject’s UPROPERTY, or call AddToRoot() to attach them to the root set, otherwise they will get garbage collected shortly after you created them.

Take a look at SMediaPlayerEditorOutput::Construct, for example.

When you’re done using your objects, make sure you clear the property that holds them / remove them from the root set, otherwise you’ll leak memory.