声音

来源:互联网 发布:医院网络咨询工作计划 编辑:程序博客网 时间:2024/04/28 19:06
紧接上面博客,设置游戏里的各种声音吧!!!


1. 各种UIbutton的点击 music

......(1) 声音控制的脚本

using UnityEngine;using System.Collections;public class UIButtonMusic : MonoBehaviour {public string mMusicName = "ui_click";// 按钮默认声音public void SetMusicName(string name){mMusicName = name;}public void PlayMusic(){if (mMusicName == "")return;MusicManager.GetInstance().PlaySoundEffect(mMusicName);}}


......(2) 改 UIButton 原脚本。。。。

  

找到  OnClick() 方法protected virtual void OnClick (){// add self code --------- YJif (Time.realtimeSinceStartup - mLastClickTime < 0.2f){return;}mLastClickTime = Time.realtimeSinceStartup;if (current == null && isEnabled){current = this;EventDelegate.Execute(onClick);current = null;PlayMusic(this.gameObject);}}public  void PlayMusic(GameObject go){UIButtonMusic com = go.gameObject.GetComponent<UIButtonMusic>();if (com == null)com = go.gameObject.AddComponent<UIButtonMusic>();com.PlayMusic();}


......(3) 如果有按钮 不是 用通用声音的话 。。 直接手动在预制体上设置。。




2. 场景内,各种小声音 (建筑升级的声音(循环播放)..  小鸟在天上飞的声音  等)

........(1)我自己的想法。。 --- 被项目pass掉了, 不过还是贴出来吧

大概思路是,放声音的建筑/鸟等,身上加MoveObjMusicCtr.cs脚本。。。然后判断这个pos在不在屏幕范围内,在就播放声音,不在就关掉声音

using UnityEngine;using System.Collections;public class MoveObjMusicCtr : MonoBehaviour {public string mMusicName = "build_up_ing";public string mLayerName = "";string laoying = "laoyingmusic";// 老鹰声音bool mMusicIsPlaying = false;Camera targetCamera ;Rect screenRect;void Start(){targetCamera = Camera.main;screenRect = new Rect(0, 0, Screen.width, Screen.height); }void OnBecameInvisible() { Debug.Log(string.Format("[{0}]不在视野内",this.gameObject.name));} void OnBecameVisible() {Debug.Log(string.Format("[{0}]在视野内",this.gameObject.name));}void OnDestory(){StopMusic();}void Update(){if (this.gameObject.activeInHierarchy == false){StopMusic();return;}if (targetCamera == null || screenRect == null){StopMusic();return;}Vector3 screenPos = targetCamera.WorldToScreenPoint(this.gameObject.transform.position);if(!screenRect.Contains(screenPos)){if (mMusicIsPlaying == true){Debug.Log(string.Format("[{0}]物体超出屏幕视野了",this.gameObject.name));StopMusic();}}else{bool iscanPlayAnim = MusicManager.GetInstance().CanPlaySoundEffect();if (iscanPlayAnim == true){if (mMusicIsPlaying == false){PlayMusic();Debug.Log(string.Format("[{0}]在视野内",this.gameObject.name));}}else{StopMusic();}}}public void PlayMusic(){if (string.IsNullOrEmpty(mLayerName))mLayerName = this.gameObject.name;mMusicIsPlaying = true;if (mLayerName == laoying)MusicManager.GetInstance().PlayMutextSoundEffect(mLayerName,mMusicName);elseMusicManager.GetInstance().PlayMutextSoundEffect(mLayerName,mMusicName,0,true);}public void StopMusic(){if (string.IsNullOrEmpty(mLayerName))mLayerName = this.gameObject.name;mMusicIsPlaying = false;MusicManager.GetInstance().StopMutexSoundEffet(mLayerName);}}

........(2) 项目选择的方法。。。。。

using UnityEngine;using System.Collections;public enum MoveObjMusicType{    MoveObjMusicType_LaoYing,// 老鹰声音  laoyingMoveObjMusicType_Common,// 通用声音 build_up_ing}public class MoveObjMusicCtr : MonoBehaviour {public string mMusicName = "build_up_ing";// 建筑升级的声音public string mLayerName = "";// 声音所在层级    public MoveObjMusicType mType = MoveObjMusicType.MoveObjMusicType_Common;// 声音类型    bool mMusicIsPlaying = false;// 是否在播放Camera targetCamera ;Rect screenRect;    private AudioSource mAudio;    private float mStopTime = 0.0f;// 普通声音的剩余时间    private float mInitVolume = 1.0f;    private float mLaoYingTime = 0.0f;// 老鹰剩余的播放声音void Start(){targetCamera = Camera.main;        int offset = -200;        int witdh = Screen.width + offset;        int height = Screen.height + offset;screenRect = new Rect(0, 0, witdh, height);        OnSwipe(null);    }    void Awake()    {        if (mLayerName == string.Empty)            mLayerName = this.gameObject.name;                if (mMusicName == StringDefine.LaoYingEffect)        {            mLaoYingTime = NGUITools.RandomRange(1, 20);            mType = MoveObjMusicType.MoveObjMusicType_LaoYing;        }        else        {            mType = MoveObjMusicType.MoveObjMusicType_Common;            mLaoYingTime = 0;        }        CameraTouch.OnSwipes.Add(OnSwipe);    }void OnBecameInvisible() {        Debuger.Log(string.Format("[{0}]不在视野内",this.gameObject.name));} void OnBecameVisible() {        Debuger.Log(string.Format("[{0}]在视野内",this.gameObject.name));}    void OnEnable()    {    }    void OnDestroy(){OnStopMusic();        CameraTouch.OnSwipes.Remove(OnSwipe);    }void Update(){        if(mLaoYingTime > 0            && mType == MoveObjMusicType.MoveObjMusicType_LaoYing)        {            mLaoYingTime -= Time.deltaTime;            if(mLaoYingTime <= 0.0f)            {                PlayMusic();            }        }        if(mStopTime > 0)        {            mStopTime -= Time.deltaTime;            if(mAudio != null)            {                float volume = mInitVolume * (1.0f - (0.5f - mStopTime) / 0.5f);                if (volume < 0)                    volume = 0;                mAudio.volume = volume;            }            if(mStopTime <= 0)            {                mStopTime = 0;                OnStopMusic();            }        }}// 播放音乐public void PlayMusic(){        if (mType == MoveObjMusicType.MoveObjMusicType_LaoYing)        {            if (mLaoYingTime > 0)                return;            mMusicIsPlaying = true;            MusicManager.GetInstance().PlayMutextSoundEffect(mLayerName, mMusicName, gameObject,0,false,0.3f);            mLaoYingTime = NGUITools.RandomRange(30, 200);        }        else        {            mMusicIsPlaying = true;            MusicManager.GetInstance().PlayMutextSoundEffect(mLayerName, mMusicName, gameObject, 0, true,0.3f);        }    }// 通知音乐public void StopMusic(){        if (mStopTime > 0)            return;        mAudio = MusicManager.GetInstance().GetMutextSoundEffect(mLayerName);        if(mAudio == null)        {            OnStopMusic();            return;        }        else        {            mInitVolume = mAudio.volume;            mStopTime = 0.5f;        }    }// 立即停止音乐    private void OnStopMusic()    {        mMusicIsPlaying = false;        MusicManager.GetInstance().StopMutexSoundEffet(mLayerName);        mAudio = null;    }// 监听相机的滑动事件    void OnSwipe(Gesture gesture)    {        if (this.gameObject.activeInHierarchy == false            || targetCamera == null            || screenRect == null)        {            StopMusic();            return;        }        if (!GetIsInScreen())        {            if (mMusicIsPlaying == false                || mType == MoveObjMusicType.MoveObjMusicType_LaoYing)                return;            Debuger.Log(string.Format("[{0}]物体超出屏幕视野了", this.gameObject.name));            StopMusic();        }        else        {            if (mMusicIsPlaying == true                || mType == MoveObjMusicType.MoveObjMusicType_LaoYing)                return;            PlayMusic();            Debuger.Log(string.Format("[{0}]在视野内", this.gameObject.name));        }    }// 是否在屏幕内    private bool GetIsInScreen()    {        Vector3 screenPos = targetCamera.WorldToScreenPoint(this.gameObject.transform.position);        return screenRect.Contains(screenPos);    }}

----------------------------------   水的声音,,,,, 水很大 所以特殊处理

using UnityEngine;using System.Collections;using System.Collections.Generic;using NTFrame;using System.Security;public class WorldMusicCtrl : SingletonMono<WorldMusicCtrl> {    public Dictionary<string ,WorldMusicData> mDatasLists = new Dictionary<string, WorldMusicData>();    public string mCurMusic = string.Empty;    private AudioSource mAudio;    private float mStopTime = 0.0f;// 普通声音的剩余时间    private float mInitVolume = 1.0f;// 加载xml    public void InitData(string xmlText)    {        mDatasLists.Clear();        SecurityElement xmlNodes = ClientTools.GetXmlListFromFile(xmlText);        foreach (SecurityElement dancer in xmlNodes.Children)        {            if (dancer.Tag == "Data")            {                string id = dancer.Attribute("Id");                string rects = dancer.Attribute("Rects");                string musicName = dancer.Attribute("MusicName");                WorldMusicData data = new WorldMusicData();                data.Init(id, musicName, rects);                mDatasLists[data.mId] = data;            }        }    }// 开始监听    public void EnterWorld()    {        WorldMapRayPosition.AddChangePosFunc(FreshXY);    }// 移除监听    public void LeaveWolrd()    {        WorldMapRayPosition.RemoveChangePosFunc(FreshXY);        mCurMusic = "";        MusicManager.GetInstance().StopMutexSoundEffet("WorldMusic");    }// 刷新位置-- 尝试播放音乐    public void FreshXY()    {        WorldMusicInfo musicName = GetMusicName(WorldMapRayPosition.CurrentXY);        PlayMusic(musicName);    }// 播放音乐    public void PlayMusic(WorldMusicInfo musicName)    {        if (musicName == null || musicName.music == "")        {            StopMusic();            return;        }        if (mCurMusic == musicName.music)        {            AudioSource sourc = MusicManager.GetInstance().GetMutextSoundEffect("WorldMusic");            if(sourc != null)            {                Vector3 temppos = WorldEntityManager.XYToWorldPostion(musicName.pos);                sourc.transform.position = temppos;            }            return;        }        mCurMusic = musicName.music;        Vector3 pos = WorldEntityManager.XYToWorldPostion(musicName.pos);        MusicManager.GetInstance().PlayMutextSoundEffect("WorldMusic",musicName.music,pos,0,true,StringDefine.SceneMusicVolume);    }// 判断这个点在不在xml数据list里     public WorldMusicInfo GetMusicName(Vector2 pos)    {        foreach(WorldMusicData data in mDatasLists.Values)        {            if (data.IsInRect(pos))                return data.GetInfo(pos);        }        return null;    }// 尝试停止音乐    public void StopMusic()    {        if (mStopTime > 0)            return;        mAudio = MusicManager.GetInstance().GetMutextSoundEffect("WorldMusic");        if (mAudio == null)        {            OnStopMusic();            return;        }        else        {            mInitVolume = mAudio.volume;            mStopTime = 0.5f;        }    }// 停止音乐    private void OnStopMusic()    {        mCurMusic = "";        MusicManager.GetInstance().StopMutexSoundEffet("WorldMusic");        mAudio = null;    }// 1. 时间到了-停止音乐 2. 刷新音量    private void Update()    {        if (mStopTime > 0)        {            mStopTime -= Time.deltaTime;            if (mAudio != null)            {                float volume = mInitVolume * (1.0f - (0.5f - mStopTime) / 0.5f);                if (volume < 0)                    volume = 0;                mAudio.volume = volume;            }            if (mStopTime <= 0)            {                mStopTime = 0;                OnStopMusic();            }        }    }}

using UnityEngine;using System.Collections.Generic;public class WorldMusicInfo{    public Vector2 pos;// 位置    public string  music;// 声音}public class WorldMusicData{    public string mId;// id    public string mMusicName; // 声音名字    public List<Rect> mRects = new List<Rect>();// 声音视野 x y 中心坐标 w h 以中心点为轴 的宽高增加    public void Init(string id, string music, string rects)    {        mId = id;        mMusicName = music;        mRects.Clear();        List<string> strs = ConfigDataTool.SplitStringDouhao(rects,';');        for(int i = 0; i < strs.Count; i++)        {            Vector4 rect = ClientTools.GetVector4ByString(strs[i]);            Rect tempRect = new Rect(rect.x - (float)rect.z / 2.0f, rect.y - (float)rect.w / 2.0f, rect.z, rect.w);            mRects.Add(tempRect);        }    }// 坐标 在不在 视野里    public bool IsInRect(Vector2 pos)    {        for(int i = 0; i < mRects.Count; i++)        {            if (mRects[i].Contains(pos))                return true;        }        return false;    }// 获取xml数据--- 通过位置    public WorldMusicInfo GetInfo(Vector2 pos)    {        for (int i = 0; i < mRects.Count; i++)        {            if (mRects[i].Contains(pos))            {                WorldMusicInfo info = new WorldMusicInfo();                info.pos = mRects[i].center;                info.music = mMusicName;                return info;            }        }        return null;    }}

读取配置的xml

0 0