unity播放音效(一)

为应用声明一个全局的音效管理脚本

step1:在最初一个Scene添加一个全局AudioSource
这里写图片描述

using UnityEngine;
using System.Collections;

public class AudioManager : MonoBehaviour {
    private static AudioManager instance= null;
    [HideInInspector]
    public AudioSource audioMgr;
    private AudioClip ac;
    private string  curMusicName = "";
    private bool allowPlay = true;
    public static AudioManager  getInstance(){
        return instance;
    }
    void Awake() {
        if (instance != null && instance != this) {
            Destroy(this.gameObject);
        } else {
            instance = this;
            audioMgr = GetComponent(typeof(AudioSource)) as AudioSource;
        }
        DontDestroyOnLoad(this.gameObject);
    }
    public bool getAllowPlay() {
        return allowPlay;
    }
    public void setAllowPlay(bool allowPlayNew)  {
        allowPlay = allowPlayNew;
    }
    public void  Play(string fileName) {
        if(!allowPlay) {
            return ;
        }
        if (!fileName.Equals(curMusicName)) {
            ac = Resources.Load("audio/"+fileName) as AudioClip;
            audioMgr.clip = ac;
            audioMgr.volume = 1f;
            audioMgr.Play();
            curMusicName = fileName;
        }
    }
    public void Stop() {
        audioMgr.Stop();
        curMusicName = "";
    }
}

step2:在最初Scene添加SoundHolder,SoundWorldHolder
这里写图片描述

这里写图片描述
step3:
背景音:
AudioManager.getInstance().setAllowPlay(true);
AudioManager.getInstance().Play(“welcome_music”);
AudioManager.getInstance().Stop();
音效:
SoundManager.getInstance().setAllowPlay(false);
SoundManager.getInstance().Clean();

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值