Unity3d声音渐变控制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HeBiReChenAi/article/details/38276551
声音渐变,主要是一个声音结构体,一个迭代器,然后去使用它,很方便。
using UnityEngine;
using System.Collections;

//声音结构点//
public struct AudioNode
{
     public AudioSource audioSource;          //声音池//
     public int volumeAdd;                    //声音变化,+1则递增,-1则递减//
     public float durationTime;               //渐变时间//
    
     //初始化构造函数//
     public AudioNode(GameObject obj,AudioClip m_clip,float m_initVolume,int m_volumeAdd,float m_durationTime)
     {
          this.audioSource =obj.AddComponent<AudioSource>();
          this.audioSource.playOnAwake = false;
          this.audioSource.volume = m_initVolume;
          this.audioSource.clip = m_clip;
          this.volumeAdd = m_volumeAdd;
          this.durationTime = m_durationTime;
     }
}

public class SoundControl : MonoBehaviour
{
    
     public AudioClip clip;
     void Start ()
     {
          AudioNode audioNode=new AudioNode(gameObject,clip,0,1,4);
          StartCoroutine("AudioSourceVolume",audioNode);
     }
     #endregion
    
     //声音渐变迭代器//
     IEnumerator AudioSourceVolume(AudioNode audioNode)
     {
          float initVolume = audioNode.audioSource.volume;
          float preTime = 1.0f/audioNode.durationTime;
          if (!audioNode.audioSource.isPlaying) audioNode.audioSource.Play();
          while(true)
          {
               initVolume += audioNode.volumeAdd * Time.deltaTime *preTime;
               if (initVolume >1 || initVolume <0)
               {
                    initVolume = Mathf.Clamp01(initVolume);
                    audioNode.audioSource.volume = initVolume;
                    if (initVolume ==0) audioNode.audioSource.Stop();
                    break;
               }else
               {
                    audioNode.audioSource.volume = initVolume;
               }
               yield return 1;
          }
     }
}

只要结构体设为共有,调用的脚本中协商迭代器就可以调用了。。。。
展开阅读全文

没有更多推荐了,返回首页