我一直在尝试学习Unity中的音频,并且遇到一个问题,即音量增加到明显降低的程度。
声音触发于
GetComponent<AudioSource>().PlayOneShot(sound);
而且似乎有时会被触发多次,从而导致音量增加,有时会出现削波。
我尝试使用
Play()
和Stop()
解决此问题,但这也导致所有其他音频也被剪切。尝试创建新的音频源并没有取得很大的成功,但这可能是由于我对此 Realm 的知识不足所致。预防此问题的最佳方法是什么?我可以从一个游戏对象中声明多个音频源,还是应该在其他地方查看?
谢谢!
最佳答案
设法修复它!
问题是,只有一个音频源可用。因此,解决方案是创建第二个音频源,并在脚本中使用
public AudioSource[] sounds;
void PlaySound (AudioClip sound)
{
sounds = GetComponents<AudioSource>();
AudioSource audioSource = sounds[1]; //Using the second AudioSource
audioSource.clip = sound;
audioSource.Stop(); //Stop any previous audio from playing
audioSource.Play();
}
非常感谢您-https://answers.unity.com/questions/52017/2-audio-sources-on-a-game-object-how-use-script-to.html
编辑:改进的代码。上面的代码再次一次只允许播放一个剪辑,因此我决定进一步介绍它,并在每个剪辑开始播放时为其创建代码。这是最终代码
public Dictionary<string,AudioSource> sounds = new Dictionary<string, AudioSource>();
void PlayOneShotSound (AudioClip sound)
{
//Check if AudioSource has been created for this clip
if (!sounds.ContainsKey(sound.name))
{
sounds.Add(sound.name, gameObject.AddComponent<AudioSource>());
}
AudioSource audioSource = sounds[sound.name]; //Using AudioSource for the clip
audioSource.clip = sound;
audioSource.Stop(); //Preventing previous sound from being played
audioSource.Play();
}
关于unity3d - AudioSource.PlayOneShot音量增加和剪辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491658/