AudioManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QFramework
{
public class AudioManager : MonoBehaviour
{
private static AudioManager instance;
public static AudioManager Instance
{
get
{
if (instance == null)
{
instance = new GameObject("AudioManager").AddComponent<AudioManager>();
DontDestroyOnLoad(instance);
}
return instance;
}
}
private AudioListener mAudioListener;
private AudioSource mMusicSource = null; //背景音乐
private void CheckAudioListener()
{
if (!mAudioListener)
{
this.gameObject.AddComponent<AudioListener>();
}
}
/// <summary>
/// 播放音效
/// </summary>
public void PlaySound(string soundName)
{
CheckAudioListener();
AudioSource audioSource = this.gameObject.AddComponent<AudioSource>();
AudioClip audioClip = Resources.Load<AudioClip>(soundName);
audioSource.clip = audioClip;
audioSource.Play();
}
//播放背景音乐
public void PlayMusic(string musicName,bool loop)
{
CheckAudioListener();
if (!mMusicSource)
{
mMusicSource = this.gameObject.AddComponent<AudioSource>();
}
AudioClip audioClip = Resources.Load<AudioClip>(musicName);
mMusicSource.clip = audioClip;
mMusicSource.loop = loop;
mMusicSource.Play();
}
}
}