Unity 将 if 语句从函数中取出

我正在构建 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

如何解决?


计时器.cs


public 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";

    }

}

http://img3.mukewang.com/6300a0870001123519181032.jpg

大话西游666
浏览 109回答 2
2回答

慕娘9325324

由于 timeLeft 用于类,因此不能在方法中声明它。将其向上移动并将代码放在开头。public class Timer : MonoBehaviour{&nbsp; &nbsp; int timeLeft;&nbsp; &nbsp; void Start()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; instruction = GetComponent<Text>();&nbsp; &nbsp; &nbsp; &nbsp; InvokeRepeating("time", 0, 1);&nbsp; &nbsp; &nbsp; &nbsp; if (SceneManager.GetActiveScene().buildIndex == 7)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeLeft = 120;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeLeft = 90;&nbsp; &nbsp; &nbsp; &nbsp; }/*&nbsp; &nbsp; &nbsp; &nbsp; timeLeft = (SceneManager.GetActiveScene().buildIndex == 7) ? 120 : 90;*/&nbsp; &nbsp; }}注释行是相同的,只是写得不同。

慕盖茨4494581

您需要定义字段,然后将语句放在方法中。例如:_timeLeftifpublic class Timer : MonoBehaviour{&nbsp; &nbsp; public Collide _collide;&nbsp; &nbsp; Text instruction;&nbsp; &nbsp; int _timeLeft;&nbsp; &nbsp; void Start()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; instruction = GetComponent<Text>();&nbsp; &nbsp; &nbsp; &nbsp; InitializeTimeLeft();&nbsp; &nbsp; &nbsp; &nbsp; InvokeRepeating("time", 0, 1);&nbsp; &nbsp; }&nbsp; &nbsp; void InitializeTimeLeft()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (SceneManager.GetActiveScene().buildIndex == 7)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _timeLeft = 120;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _timeLeft = 90;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; void time()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP