Loading Next Scene bug

Hi there,

Disclosure: I just picked up unity and C# last week so this will come off as a newbie question.

Intended purpose: When player presses “Space”, the next scene will be initiated.

Details:
I got the Build Settings all set up, have 2 scenes in it. Created object named LevelManager, got it linked with the “Menu” scene with it is the script required to run the function.

public class LevelManager : MonoBehaviour {

    //Load Scene
    int currentIndex = SceneManager.GetActiveScene().buildIndex;

    // Use this for initialization
    void Start ()
    {

    }
	
	// Update is called once per frame
	void Update () {

        // This will initiate the scene "1" as per Build Settings

        if (Input.GetKeyDown(KeyCode.Space))
        {
            LoadNextScene();
        }

    }

    void LoadNextScene()
    {
        SceneManager.LoadScene(currentIndex + 1);
    }
}

Problem:
It takes 2 spaces instead of 1 to get to the next scene.
Also getting this error via console

UnityException: INTERNAL_CALL_GetActiveScene is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'LevelManager'.
See "Script Serialization" page in the Unity Manual for further details.

Suggestions would be greatly appreciated.
Thanks for your help

Hi, you just need to declare your current index when the scene has actually started so it returns the correct index, at the moment it’s declared beforehand so it’s returning an incorrect value. Here’s the code:

public int currentIndex;

void Start () {
        currentIndex = SceneManager.GetActiveScene().buildIndex;
}

Enjoy Unity! :slight_smile: