Unity全局AudioSource管理

1.先写一个单例模式保证全局只有一个音频管理的物体

 1 public class Singleton<T> : MonoBehaviour where T : Singleton<T>
 2 {
 3     public static T Instance { get; private set; }
 4 
 5     protected void Awake()
 6     {
 7         if (Instance == null)
 8         {
 9             Instance = (T)this;
10             DontDestroyOnLoad(gameObject);//<切换场景不销毁物体>
11         }
12         else
13         {
14             Destroy(gameObject);
15         }
16     }
17 }

2.获取绑定物体上的AudioSource组件

 1 public class AudioManager : Singleton<AudioManager>
 2 {
 3     private AudioSource m_audioSource;
 4 
 5     public AudioSource AudioSource
 6     {
 7         get
 8         {
 9             if (m_audioSource == null)
10             {
11                 m_audioSource = transform.GetComponent<AudioSource>();
12             }
13             return m_audioSource;
14         }
15     }
16 
17 
18     private new void Awake()
19     {
20         base.Awake();
21     }
22 }

 

posted @ 2022-01-13 15:14  法小鱿  阅读(300)  评论(0编辑  收藏  举报