lundi 29 mars 2021

Scene randomizer issue

I’m developing a casual 2D Game on unity. And I’m a little stuck. I have 2 scripts: one loads when the game starts - (MainMenuScript.cs), one loads when every scene starts - (LevelControlScript.cs)

I need to randomize scenes, but index_scene = UnityEngine.Random.Range(a, b) not quite what I need in my case. But I still need to show scenes in random sequence. I wrote this code where:

MainMenuScript.cs:

  1. Creates a list, where we put played scenes. It should be initialized once on loading.

LevelControlScript.cs:

  1. Chooses the next scene randomly and check it with the values in the list.

  2. If the list includes that scene - choose another random scene, if it’s not in the list - it plays and after that the scene should be added to the list of played scenes.

  3. When all the scenes were played - the list should be cleared.

So, it should rotate until I manually leave the level.

However, I don’t understand why unity shows this error and how to fix it: NullReferenceException: Object reference not set to an instance of an object LevelControlScript.LoadNextLevel () (at Assets/Scripts/LevelControlScript.cs:606)

MainMenuScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenuScript : MonoBehaviour {

    public List<int> remember = new List<int>(); //here

    public void StartLvl()
    {
        SceneManager.LoadScene("Scenes/LVL");
    }

    public void Quit()
    {
        Application.Quit();
    }
}

LevelControlScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LevelControlScript : MonoBehaviour {

    MainMenuScript mainmenu; //here

    // Variable to contain current scene build index
    int currentSceneIndex;
    void Start() {

        mainmenu = GetComponent<MainMenuScript>(); //here
        
        // Getting current scene build index
        currentSceneIndex = SceneManager.GetActiveScene().buildIndex;    
    }

    // Method is invoked when correct answer is given
    public void RightAnswer()
    {
        Code...    
    }

    // Method loads next level
    public void LoadNextLevel()
    {
        int index_scene = UnityEngine.Random.Range(1, 10);
        foreach (int index in mainmenu.remember)
        {
            if (index == index_scene)
            {
                index_scene = UnityEngine.Random.Range(1, 10);
            }
        }
        if (mainmenu.remember.Count == 10)
        {
            mainmenu.remember.Clear();
        }
        mainmenu.remember.Add(index_scene);
        SceneManager.LoadScene(index_scene);
    }
}



Aucun commentaire:

Enregistrer un commentaire