https://www.youtube.com/watch?v=6OT43pvUyfY&t=9s
使用单例来进行管理
using UnityEngine.Audio;
using UnityEngine;
using System;
public class AudioManager: MonoBehaviour{
public Sound[] sounds;
public static AudioManager instance;
void Awake(){
if(instance == null)
instance = this;
else {
Destroy(gameObject);
return;
}
DonDestroyOnLoad(gameObject);
foreach(Sound s in sounds){
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
public void Play(string name){
Sound s = Array.Find(sounds, sound => sound.name == name);
if(s == null){
Debug.LogWarning("Sound:"+ name + "not found! ");
return;
}
s.source.play();
}
}
}
创建sound
using UnityEngine.Audio;
using UnityEngine;
[System.Serializable]
public class Sound{
public string name;
public AudioClip clip;
[Range(0f,1f)]
public float volume;
[Range(0f,3f)]
public float pitch;
[HideInInspecetor]
public AudioSource source;
public bool loop;
}
···
调用
FindObjectOfType<AudioManager>().Play("PlayDeath");
网友评论