如何解决如何在新场景中更改 DontDestroyOnLoad 的 AudioSource 的 AudioClip?
我有几个不同的场景,我想在特定场景中播放不同的曲调。我创建了一个游戏对象并附加了一个音频剪辑和一个脚本。该脚本基本上可以防止 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
不会产生任何效果。
为 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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。