using System; using System.Collections.Generic; using UnityEngine; namespace BuffaloSiege { public class GameAudio:MonoBehaviour { AudioSource effects,music;SaveStore store;readonly Dictionary clips=new Dictionary();float lastShot;bool hasEnteredLobby; public void Initialize(SaveStore s) {store=s;hasEnteredLobby=false;if(!effects){effects=gameObject.AddComponent();effects.playOnAwake=false;}if(!music){music=gameObject.AddComponent();music.playOnAwake=false;music.loop=true;music.volume=.13f;music.clip=MakeMusic();}Sync();} public void EnterLobby(){if(hasEnteredLobby)return;hasEnteredLobby=true;Sync();} public void Sync(){if(music==null||store==null)return;bool shouldPlay=hasEnteredLobby&&store.Data.music;if(shouldPlay&&!music.isPlaying)music.Play();else if(!shouldPlay)music.Stop();} public void Play(string key) { if(store==null||!store.Data.sfx||effects==null)return;bool shot=key=="archer"||key=="pistol"||key=="crossbow"||key=="rifle"||key=="mortar";if(shot&&Time.unscaledTime-lastShot<.035f)return;if(shot)lastShot=Time.unscaledTime; if(!clips.TryGetValue(key,out var c)){float a=620,b=280,d=.075f;bool noise=false; switch(key){case "coin":a=880;b=1320;break;case "build":a=420;b=900;d=.16f;break;case "wave":a=330;b=520;d=.22f;break;case "freeze":a=1200;b=300;d=.4f;break;case "boom":case "mortar":a=160;b=40;d=.3f;noise=true;break;case "error":a=220;b=120;d=.15f;break;case "win":a=520;b=1040;d=.8f;break;case "lose":a=360;b=90;d=.65f;break;} c=Tone(key,a,b,d,noise);clips[key]=c; }effects.PlayOneShot(c,shot?.18f:.42f); } AudioClip Tone(string name,float a,float b,float duration,bool noise) {int rate=22050,n=(int)(rate*duration);var data=new float[n];double phase=0;var rand=new System.Random(19);for(int i=0;i