亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Unity 將 if 語句從函數中取出

Unity 將 if 語句從函數中取出

C#
大話西游666 2022-08-20 16:50:54
我正在構建 Unity 3D 游戲,如果用戶處于第三級,我想簽入腳本。如果為 true,則否則 .我嘗試將這個簡單的if語句實現到腳本中,但我得到了:timeLeft = 120;timeLeft = 90;Invalid token 'if' in class, struct, or interface member declaration如果我將語句放入 start 方法中,我得到:The name 'timeLeft' does not exist in the current context如何解決?計時器.cspublic class Timer : MonoBehaviour{    public Collide _collide;    Text instruction;        private void Start()    {        instruction = GetComponent<Text>();        InvokeRepeating("time", 0, 1);    }    if (SceneManager.GetActiveScene().buildIndex == 7)         int timeLeft = 120;    else int timeLeft = 90;        private void time()    {        int buildIndex = SceneManager.GetActiveScene();                if (_collide.obji <= 0 && timeLeft > 0)            SceneManager.LoadScene(buildIndex switch { 1 => 2, 3 => 5, 7 => 9 });        else if (_collide.obji > 0 && timeLeft <= 0)            SceneManager.LoadScene(buildIndex switch { 1 => 3, 3 => 6, 7 => 8 });               if (timeLeft > 0)        {            timeLeft -= 1;            instruction.text = (timeLeft).ToString();        }        else if (timeLeft <= 0)            instruction.text = "0";    }}
查看完整描述

2 回答

?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

由于 timeLeft 用于類,因此不能在方法中聲明它。將其向上移動并將代碼放在開頭。


public class Timer : MonoBehaviour

{

    int timeLeft;

    void Start()

    {

        instruction = GetComponent<Text>();

        InvokeRepeating("time", 0, 1);


        if (SceneManager.GetActiveScene().buildIndex == 7)

        {

            timeLeft = 120;

        }

        else

        {

            timeLeft = 90;

        }

/*

        timeLeft = (SceneManager.GetActiveScene().buildIndex == 7) ? 120 : 90;

*/

    }

}

注釋行是相同的,只是寫得不同。


查看完整回答
反對 回復 2022-08-20
?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

您需要定義字段,然后將語句放在方法中。例如:_timeLeftif


public class Timer : MonoBehaviour

{

    public Collide _collide;

    Text instruction;


    int _timeLeft;


    void Start()

    {

        instruction = GetComponent<Text>();

        InitializeTimeLeft();

        InvokeRepeating("time", 0, 1);

    }


    void InitializeTimeLeft()

    {

        if (SceneManager.GetActiveScene().buildIndex == 7)

        {

            _timeLeft = 120;

        }

        else

        {

            _timeLeft = 90;

        }

    }


    void time()

    {

       ...

    }

}


查看完整回答
反對 回復 2022-08-20
  • 2 回答
  • 0 關注
  • 121 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號