与C#if语句混淆

时间:2018-06-08 02:01:31

标签: c# unity3d

所以我最近开始从VB.net开始在C#中编写Unity编码,我似乎无法弄清楚为什么下面的代码无法正常工作。该程序设置为通过播放SquaresLoop1开始,但它立即切断,空间按下没有响应。

我希望程序做的是在空格键按下的SquaresLoops之间切换。

int state = 0;

void Start()
{
    audio = gameObject.GetComponent<AudioSource>();
}

void Update()
{
    if (Input.GetKeyDown("space"));
    {
        if (state == 0)
        {
            audio.clip = SquaresLoop1;
            audio.Play();
            int state = 1;
        }

        if (state == 1)
        {
            audio.clip = SquaresLoop2;
            audio.Play();
            int state = 0;
        }
    }               
}

1 个答案:

答案 0 :(得分:3)

现在我不是Unity C#的专家,但是在if语句语法不正确之后,我几乎肯定会有一个分号; - 它应该只是是一个大括号。

试试这个:

int state = 0;

void Start(){
    audio = gameObject.GetComponent<AudioSource>();
}

void Update(){
    if (Input.GetKeyDown("space")){ // this was the offending line
        if (state == 0){
            audio.clip = SquaresLoop1;
            audio.Play();
            state = 1; // you don't need to re-declare state's type when setting it's value
        } else {
            audio.clip = SquaresLoop2;
            audio.Play();
            state = 0;
        }
    }               
}