
函数SoundManagement:
- 校验成员变量
BGMusic(UAudioComponent),有效则立刻 Stop 停止旧背景音乐。 - 使用
SpawnSound2D生成 2D 音频组件,赋值给BGMusic。 - 校验新生成的音频组件,有效就调用 Play,从 0 秒开始播放。
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include “CoreMinimal.h”
#include “GameFramework/Actor.h”
#include <Components/AudioComponent.h>
#include “MyLevelManager.generated.h”
UCLASS()
class ROUGHLIKE1_API AMyLevelManager : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor’s properties
AMyLevelManager();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
private:
//保存当前背景音乐
UPROPERTY()
UAudioComponent* BGMusic;
UFUNCTION(BlueprintCallable, Category = "Sound")
void SoundManagement(USoundBase* sound);
};
// Fill out your copyright notice in the Description page of Project Settings.
#include “MyLevelManager.h”
#include <Kismet/GameplayStatics.h>
// Sets default values
AMyLevelManager::AMyLevelManager()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don’t need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMyLevelManager::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMyLevelManager::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMyLevelManager::SoundManagement(USoundBase* sound)
{
//如果旧bgm有效,立即停止播放音乐
if (IsValid(BGMusic))
{
BGMusic->Stop();
}
//生成2d音频组件
UAudioComponent* newBGM = UGameplayStatics::SpawnSound2D(GetWorld(), sound);
//赋值给BGMUSIC
BGMusic = newBGM;
//有效则播放
if (IsValid(BGMusic))
{
BGMusic->Play(0.0);
}
}
转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/directx3d_beginner/article/details/166140491



