UnityC#Unity笔记-声音管理器
Wang ChenHan管理器
导入消息框架(详见之前的Unity笔记),新建一个Manager文件夹,用来储存管理器。再创建一个Managers文件夹,是管理器的集合。
声音管理器
在Managers下创建脚本Managers。
1 2 3 4 5 6 7 8 9
| using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Managers { }
|
这个类管理所有的管理器单例。下面创建一个简单的声音管理器
创建一个名为AudioManager的文件夹,里面创建一个名为AudioManager的脚本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine;
public class AudioManager : ManagerBase { private AudioSource envPlayer;
private AudioSource sePlayer; private AudioSource Player; void Start() { Player = gameObject.AddComponent<AudioSource>(); Player.loop = true; sePlayer = gameObject.AddComponent<AudioSource>(); envPlayer = gameObject.AddComponent<AudioSource>(); GameObject.DontDestroyOnLoad(this.gameObject); }
void Update() { } public override byte GetMessageType() { return MessageType.Type_Audio; } 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){ Player.volume = volume; Player.clip = clip; if(Player.isPlaying){ Player.Stop(); } Player.clip = clip; Player.Play(); } public void StopMusic(){ Player.Stop(); } public void ChangeMusicVolume(float volume){ Player.volume = volume; } public void PlayEnvMusic(string name,float volume){ AudioClip clip = Resources.Load<AudioClip>(name); PlayEnvMusic(clip,volume); } public void PlayEnvMusic(AudioClip clip,float volume){ if(envPlayer.isPlaying){ envPlayer.Stop(); } envPlayer.clip = clip; envPlayer.volume = volume; envPlayer.Play(); } public void StopEnvMusic(){ envPlayer.Stop(); } public void PlaySeSound(string name,float volume=1){ AudioClip clip = Resources.Load<AudioClip>(name); PlaySeSound(clip,volume); } public void PlaySeSound(AudioClip clip,float volume=1){
sePlayer.PlayOneShot(clip,volume); } public void PlayerSeSoundOnObject(string name,GameObject go,float volume=1){ AudioClip clip = Resources.Load<AudioClip>(name); PlayerSeSoundOnObject(clip,go,volume); } public void PlayerSeSoundOnObject(AudioClip clip,GameObject go,float volume=1){ AudioSource player = go.GetComponent<AudioSource>(); if(player == null){ player = go.AddComponent<AudioSource>();; } player.volume = volume; player.PlayOneShot(clip); } }
|
然后在Managers脚本上编写:
1 2 3 4 5 6 7 8 9 10 11
| using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Managers { public static AudioManager m_Audio = AudioManager.Instance.GetComponent<AudioManager>(); }
|