在创建声音管理器之前,我们先创建一个空的类Manager用于保存所有的管理器单例,这样之后要用到管理器时,直接调用Manager类即可。每创建一个管理器类,都要在Manager类进行注册
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Manager
{
public static AudioManager m_Audio = AudioManager.Instance;
}
声音管理器完整代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : ManagerBase<AudioManager>
{
// environment sound
private AudioSource envPlayer;
// sound effect
private AudioSource sePlayer;
// music
private AudioSource Player;
// Start is called before the first frame update
void Start()
{
envPlayer = gameObject.AddComponent<AudioSource>();
sePlayer = gameObject.AddComponent<AudioSource>();
Player = gameObject.AddComponent<AudioSource>();
// do not destroy audio manager when switching scene
GameObject.DontDestroyOnLoad(gameObject);
}
// play music
public void PlayMusic(string name, float volume = 1) {
AudioClip clip = Resources.Load<AudioClip>(name);
PlayMusic(clip, volume);
}
public void PlayMusic(AudioClip clip, float volume = 1)