using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sound : MonoSingleton<Sound>
{
AudioSource m_Bg;//背景音乐
AudioSource m_effect;//音效
public string ResourcesDir = "";
protected override void Awake()
{
base.Awake();
m_Bg = gameObject.AddComponent<AudioSource>();//添加AudioSource组件
m_Bg.playOnAwake = false;//先不播放
m_Bg.loop = true;//循环播放
m_effect = gameObject.AddComponent<AudioSource>();
}
//播放背景音乐
public void PlayBG(string audioName)
{
string oldName;
if(m_Bg.clip == null)
{
oldName = "";
}
else
{
oldName = m_Bg.clip.name;
}
//判断是否正在播放
if (oldName != audioName)
{
//加载资源 clip
string path = ResourcesDir + "/" + audioName;
AudioClip clip = Resources.Load<AudioClip>(path);
//播放
if(clip != null)
{
m_Bg.clip = clip;
m_Bg.Play();
}
}
}
//播放音效
public void PlayEffect(string audioName)
{
//加载资源 clip
string path = ResourcesDir + "/" + audioName;
AudioClip clip = Resources.Load<AudioClip>(path);
//播放一次
m_effect.PlayOneShot(clip);
}
}
unity 动态播放音乐和音效
猜你喜欢
转载自blog.csdn.net/cuijiahao/article/details/103973092
今日推荐
周排行