Unity - 导入声音以在按键上播放

时间:2015-08-22 16:50:24

标签: c# unity3d

我有以下代码,但我没有得到任何类型的错误,很多谷歌搜索没有得到任何答案

我做错了什么?

public class FirstPage : MonoBehaviour {

public AudioSource mySound;

// Use this for initialization
void Start () {
    mySound = Resources.Load("05 - Listen to the Man_[plixid.com]") as AudioSource;
}

void Update () {
if(Input.GetKeyUp(KeyCode.Space)){
        mySound.Play();

    };
}

}

2 个答案:

答案 0 :(得分:1)

这可能是因为您尝试加载AudioSource而不是AudioClip

正确的方法是加载音频片段,将其分配给音频源,然后使用AudioSource.Play()播放片段

public class FirstPage : MonoBehaviour {

    public AudioSource mySound;

    // Use this for initialization
    void Start () {
        var audioClip = Resources.Load<AudioClip>("05 - Listen to the Man_[plixid.com]");  //Load the AudioClip from the Resources Folder
        mySound.clip = audioClip;  //Assign it as AudioSource's clip
    }

    void Update () {
        if(Input.GetKeyUp(KeyCode.Space)){
            mySound.Play();
        }  //Also, I removed the extra semi-colon you had here
    }
}

答案 1 :(得分:0)

是&#34; 05 - 听Man_ [plixid.com]&#34;项目中的资产?如果不是,我相信这就是为什么它不会起作用。我非常确定Resources.Load仅用于将现有资源加载到RAM中,以便在您需要时准备就绪。

我做了一些调查,你可能会发现this thread很有用,以及Unity参考文档中的this page

这里有一个来自那里的JS样本应该可以解决这个问题。希望你能够轻松地翻译成C#,如果这是你喜欢的那样:)

dismissViewControllerAnimated
相关问题