【问题标题】:How to change DontDestroyOnLoad'ed AudioSource's AudioClip on a new scene?如何在新场景中更改 DontDestroyOnLoad ed AudioSource 音频剪辑?
【发布时间】:2021-02-28 21:15:28
【问题描述】:

我有几个不同的场景,我想在特定场景中播放不同的曲调。我创建了一个游戏对象并附加了一个音频剪辑和一个脚本。该脚本基本上使 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;
    }
}

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

【问题讨论】:

    标签: c# unity3d audio-source


    【解决方案1】:

    请注意,仅更改 clip 将无效。

    clip 分配新的音频剪辑不会立即更改正在播放的剪辑。

    您还必须通过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();
    

    或者去掉对源的公开访问,使用我已经添加的方法

    OSTPlayer.Instance.PlayClip(clip);  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多