我制作了一个脚本,该脚本吸收了游戏的所有声音并对其进行排序。当我下达命令播放脚本时,脚本运行良好,并在编辑器中提供了所有声音,但是当我构建游戏时,声音不起作用。我不知道问题出在哪里,但是我通过音频源直接添加的其他声音在构建时效果很好。我也需要脚本添加的声音才能在构建中使用。
音频管理器脚本:
using UnityEngine;
[System.Serializable]
public class Sound {
public string name;
public AudioClip clip;
[Range (0f, 1f)]
public float volume = 0.7f;
[Range (0.5f, 1.5f)]
public float pitch = 1f;
[Range (0f, 0.5f)]
public float randomVolume = 0.1f;
[Range (0f, 0.5f)]
public float randomPitch = 0.1f;
public bool loop = false;
private AudioSource source;
public void SetSource (AudioSource _source) {
source = _source;
source.clip = clip;
source.loop = loop;
}
public void Play () {
source.volume = volume * (1 + Random.Range (-randomVolume / 2f, randomVolume / 2f));
source.pitch = pitch * (1 + Random.Range (-randomPitch / 2f, randomPitch / 2f));
source.Play ();
}
public void Stop () {
source.Stop ();
}
}
public class AudioManager : MonoBehaviour {
public static AudioManager instance;
[SerializeField]
Sound[] sounds;
void Awake () {
if (instance != null) {
if (instance != this) {
Destroy (this.gameObject);
}
} else {
instance = this;
DontDestroyOnLoad (this);
}
}
void Start () {
for (int i = 0; i < sounds.Length; i++) {
GameObject _go = new GameObject ("Sound_" + i + "_" + sounds[i].name);
_go.transform.SetParent (this.transform);
sounds[i].SetSource (_go.AddComponent<AudioSource> ());
}
}
public void PlaySound (string _name) {
for (int i = 0; i < sounds.Length; i++) {
if (sounds[i].name == _name) {
sounds[i].Play ();
return;
}
}
// no sound with _name
Debug.LogWarning ("AudioManager: Sound not found in list, " + _name);
}
public void StopSound (string _name) {
for (int i = 0; i < sounds.Length; i++) {
if (sounds[i].name == _name) {
sounds[i].Stop ();
return;
}
}
// no sound with _name
Debug.LogWarning ("AudioManager: Sound not found in list, " + _name);
}
}