如何在新场景中更改 DontDestroyOnLoad ed AudioSources Audio Clip?

How to change DontDestroyOnLoad'ed AudioSource's AudioClip on a new scene?

我有几个不同的场景,我想在特定场景中播放不同的曲调。我创建了一个游戏对象并附加了一个音频剪辑和一个脚本。该脚本基本上使 Unity 远离破坏。所以它可以在不同的场景播放。

using UnityEngine;

public class OSTPlayer : MonoBehaviour
{
    private static OSTPlayer instance = null;

    private static OSTPlayer Instance
    {
        get { return instance; }
    }

    private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(this.gameObject);
            return;
        }
        else
        {   instance = this;   }
        DontDestroyOnLoad(this.gameObject);
    }
}

在特定场景中,我想更改音频片段,以便播放不同的声音文件。我在下面写了一段代码(附在一个空的游戏对象上),它看起来改变了音频剪辑。但是没有声音传来,就像停止播放一样。

using UnityEngine;
using UnityEngine.SceneManagement;

public class StreetNavigate : MonoBehaviour
{
    public AudioClip clip1;//I am dragging n dropping from the editor

    private AudioSource BGMaudioSource;

    private void Start()
    {
        BGMaudioSource = GameObject.FindGameObjectWithTag("OST1").GetComponent<AudioSource>();
        BGMaudioSource.clip = clip1;
    }
}

是我做错了还是出了什么问题?

请注意,仅更改 clip 不会有任何效果。

Assigning clip with a new audio clip does not instantly change the clip that is being played.

您还必须通过 Play(重新)开始播放它!


让事情变得简单一点:

您已经有了单例模式,因此您可以简单地制作它 public 并执行

public class OSTPlayer : MonoBehaviour
{
    // If possible already reference this via the Inspector
    [SerializeField] private AudioSource _audioSource;

    public AudioSource AudioSource => _audioSource;

    // Others can only read
    // Only this class can set the value
    public static OSTPlayer Instance {get; private set;}

    private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(this.gameObject);
            return;
        }
         
        instance = this;
        DontDestroyOnLoad(this.gameObject);

        // As fallback get it on runtime ONCE
        if(!_audioSource) _audioSource = GetComponent<AudioSource>();
    }

    public void PlayClip(AudioClip clip)
    {
        _audioSource.clip = clip;
        _audioSource.Play();
    }
}

然后在任何脚本中您都可以通过

简单地访问它
OSTPlayer.Instance.AudioSource.clip = clip;   
OSTPlayer.Instance.AudioSource.Play();

或者删除 public 对源的访问并使用我已经添加的方法

OSTPlayer.Instance.PlayClip(clip);