添加按钮单击Sound Unity3D 5.4

时间:2016-10-25 15:53:12

标签: button audio unity3d onclick

我一直在尝试在Unity3D游戏中为按钮添加按钮点击声音。但是,我试过的所有东西(见下文)都没有产生预期的效果(点击声音。)按钮有效但不产生声音。以下链接包含我尝试过的内容以及我最近的脚本尝试。音频设置为从检查器播放(按照最后一个链接),这就是脚本本身没有audioSource.play()的原因。我希望在单击按钮时播放声音:

http://answers.unity3d.com/questions/26241/play-sound-when-gui-button-is-pressed.html http://answers.unity3d.com/questions/182754/play-sound-on-button-press.html http://answers.unity3d.com/questions/857810/play-audio-from-46-ui-button-on-click-script.html

private AudioSource audioSource;
private float audioTimer;
public void LoadLevel(string name)
{
    StartCoroutine(AudioLength(audioTimer));
    SceneManager.LoadScene(name);
}
public void Next(string name)
{
    StartCoroutine(AudioLength(audioTimer));
    SceneManager.LoadScene(name);
}

void Start()
{
    audioSource = this.GetComponent<AudioSource>();
    audioTimer = audioSource.clip.length;
}

void Update()
{
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        SceneManager.LoadScene("Start Menu");
    }
    else if(Input.GetKeyDown(KeyCode.Q))
    {
        Application.Quit();
    }
}   

IEnumerator AudioLength(float audioTimer)
{
    yield return new WaitForSeconds(audioTimer);
}

1 个答案:

答案 0 :(得分:0)

我在community.gamedev.tv的两个人的帮助下发现了答案。

首先,问题是由音频有机会播放之前的场景变化引起的。其次,我必须将我的LoadScene添加到我的Coroutine中,以便让它处理延迟,然后加载下一个场景。我还必须通过我的协程将name变量作为字符串传递。