Проблема с переход по активной сцене

Программирование на Юнити.

Проблема с переход по активной сцене

Сообщение eis0993 10 ноя 2019, 21:13

Есть Главное меню через которое я загружаю новую игру. Главное меню = Scene(0), активная игра = Scene(1) После использования команды
Синтаксис:
Используется csharp
public void PlayButton()
        {
            SceneManager.LoadScene(1);
        }

происходит загрузка новой сцены, но уровень загруженной сцены = 2 а не 1. И при переходе на следующий уровень, переходит не на 2 а на 4. Из-за этого очки еды персонажа = 0 когда должны быть равны значению набраному в другом уровне. В чем причина? Не могу разобраться. Код GameManager.cs который отвечает за загрузку уровня:
Синтаксис:
Используется csharp
public class GameManager : MonoBehaviour
        {
                public float levelStartDelay = 2f;                                              //Time to wait before starting level, in seconds.
                public float turnDelay = 0.1f;                                                  //Delay between each Player turn.
                public int playerFoodPoints = 100;                                              //Starting value for Player food points.
                public static GameManager instance = null;                              //Static instance of GameManager which allows it to be accessed by any other script.
                [HideInInspector] public bool playersTurn = true;               //Boolean to check if it's players turn, hidden in inspector but public.
               
               
                private Text levelText;                                                                 //Text to display current level number.
                private GameObject levelImage;                                                  //Image to block out level as levels are being set up, background for levelText.
                private BoardManager boardScript;                                               //Store a reference to our BoardManager which will set up the level.
                private int level = 1;                                  //Current level number, expressed in game as "Day 1".
        private List<Enemy> enemies;                                                    //List of all Enemy units, used to issue them move commands.
                private bool enemiesMoving;                                                             //Boolean to check if enemies are moving.
                private bool doingSetup = true;                         //Boolean to check if we're setting up board, prevent Player from moving during setup.


        private void Start()
        {
            SceneManager.GetActiveScene();
         }
//Awake is always called before any Start functions
        void Awake()
                {
            //Check if instance already exists
            if (instance == null)

                //if not, set instance to this
                instance = this;

            //If instance already exists and it's not this:
            else if (instance != this)

                //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
                Destroy(gameObject);   
                       
                        //Sets this to not be destroyed when reloading scene
                        DontDestroyOnLoad(gameObject);
                       
                        //Assign enemies to a new List of Enemy objects.
                        enemies = new List<Enemy>();
                       
                        //Get a component reference to the attached BoardManager script
                        boardScript = GetComponent<BoardManager>();
                       
                        //Call the InitGame function to initialize the first level
                        InitGame();
                }

        //this is called only once, and the paramter tell it to be called only after the scene was loaded
        //(otherwise, our Scene Load callback would be called the very first load, and we don't want that)
       [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        static public void CallbackInitialization()
        {
            //register the callback to be called everytime the scene is loaded
            SceneManager.sceneLoaded += OnSceneLoaded;
        }

        //This is called each time a scene is loaded.
        static private void OnSceneLoaded(Scene arg0, LoadSceneMode arg1)
        {
           instance.level++;
           instance.InitGame();
        }

               
                //Initializes the game for each level.
                void InitGame()
                {
                        //While doingSetup is true the player can't move, prevent player from moving while title card is up.
                        doingSetup = true;
                       
                        //Get a reference to our image LevelImage by finding it by name.
                        levelImage = GameObject.Find("LevelImage");
                       
                        //Get a reference to our text LevelText's text component by finding it by name and calling GetComponent.
                        levelText = GameObject.Find("LevelText").GetComponent<Text>();
                       
                        //Set the text of levelText to the string "Day" and append the current level number.
                        levelText.text = "Day " + level;
                       
                        //Set levelImage to active blocking player's view of the game board during setup.
                        levelImage.SetActive(true);
                       
                        //Call the HideLevelImage function with a delay in seconds of levelStartDelay.
                        Invoke("HideLevelImage", levelStartDelay);
                       
                        //Clear any Enemy objects in our List to prepare for next level.
                        enemies.Clear();
                       
                        //Call the SetupScene function of the BoardManager script, pass it current level number.
                        boardScript.SetupScene(level);
                       
                }
               
eis0993
UNец
 
Сообщения: 2
Зарегистрирован: 10 ноя 2019, 21:01

Re: Проблема с переход по активной сцене

Сообщение ~AvA~ 11 ноя 2019, 13:25

Ошибка где-то у тебя в скриптах, может дебагом пройдёшься чем мы тут будем гадать?

Вопрос: Чисто интересно, зачем нужно вот это - ты же результат все равно нигде не сохраняешь, есть какая-то скрытая нужда?
Синтаксис:
Используется csharp
private void Start()
        {
            SceneManager.GetActiveScene();
         }
Аватара пользователя
~AvA~
UNIверсал
 
Сообщения: 396
Зарегистрирован: 17 фев 2015, 13:09

Re: Проблема с переход по активной сцене

Сообщение seaman 11 ноя 2019, 19:43

Каждый раз при загрузке сцены прицепляется += OnSceneLoaded; В конце метода OnSceneLoaded открепляйте его -= OnSceneLoaded;
seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Проблема с переход по активной сцене

Сообщение eis0993 11 ноя 2019, 22:29

seaman писал(а):Каждый раз при загрузке сцены прицепляется += OnSceneLoaded; В конце метода OnSceneLoaded открепляйте его -= OnSceneLoaded;

слушай, а подскажи пожалуйста как правильно записать. А то я вводил, и оно работало не так. Да, загружалось и показывало что 1й день, но после прохождения левела, опять 1й день.
eis0993
UNец
 
Сообщения: 2
Зарегистрирован: 10 ноя 2019, 21:01


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 14