Unity помещает оператор if из функции - PullRequest
0 голосов
/ 02 февраля 2019

Я создаю игру Unity 3D и хочу проверить в скрипте, находится ли пользователь на третьем уровне.Если true, то timeLeft = 120; в противном случае timeLeft = 90;.Я попытался реализовать этот простой оператор if в сценарии, но я получил:

Invalid token 'if' in class, struct, or interface member declaration

Если я поместил оператор в метод start, я получил:

The name 'timeLeft' does not exist in the current context

Как это исправить?

Timer.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour
{
    public Collide _collide;
    Text instruction;
    void Start()
    {
        instruction = GetComponent<Text>();
        InvokeRepeating("time", 0, 1);


    }


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

            int timeLeft = 120;
}
        else
        {
            int timeLeft = 90;
        }
    void time()
    {

        if (_collide.obji <= 0 && timeLeft > 0)
        {
            if (SceneManager.GetActiveScene().buildIndex == 1)
            {
                SceneManager.LoadScene(2);
            }
            else if(SceneManager.GetActiveScene().buildIndex == 4)
            {
                SceneManager.LoadScene(5);
            }
            else if (SceneManager.GetActiveScene().buildIndex == 7)
            {
                SceneManager.LoadScene(9);
            }
        }
        else if (_collide.obji > 0 && timeLeft <= 0)
        {
            if (SceneManager.GetActiveScene().buildIndex == 1)
            {
                SceneManager.LoadScene(3);
            }
            else if (SceneManager.GetActiveScene().buildIndex == 4) {
                SceneManager.LoadScene(6);
            }
            else if (SceneManager.GetActiveScene().buildIndex == 7)
            {
                SceneManager.LoadScene(8);
            }
        }

        if (timeLeft > 0)
        {
            timeLeft -= 1;
            instruction.text = (timeLeft).ToString();
        }
        else if (timeLeft <= 0) {
            instruction.text = "0";
        }

        // Update is called once per frame



    }
}

View

Ответы [ 2 ]

0 голосов
/ 02 февраля 2019

Вам необходимо определить поле _timeLeft, а затем поместить оператор if в метод.Например:

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()
    {
       ...
    }
}
0 голосов
/ 02 февраля 2019

Поскольку 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;
*/
    }
}

Комментированная строка такая же, только написано иначе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...