Changing a scene with a click of an object?

Hi I am trying to make it so when I click on a certain object in my current scene it would change to another scene. I am trying to use

using UnityEngine.SceneManagement;
using System.Collections;

public class NextLevel {

void OnMouseDown ()
{
    SceneManager.LoadScene(Level2);
}

}

Whenever I do that it says Level2 does not exist in the current context… I don’t know if i’m doing it wrong or what. I have a scene named Level2 in my scenes folder. Any help would be appreciated.

1 Answer

1

Your forgot the double quotes, so Level2 is interpreted as a variable, but there is no declared variable called Level2 in your script. Hence this variable does not exist and it cannot be called.

You need to either use “Level2” as a string or create a Level2 variable.
You also need to make NextLevel inherit from MonoBehaviour, or you will not be able to use it in your scene.

using UnityEngine;
using UnityEngine.SceneManagement; 

public class NextLevel : MonoBehaviour
{
     void OnMouseDown ()
     {
         SceneManager.LoadScene("Level2");
     }
}

But assigning a variable in the inspector would be better practice, as it will allow you to change the scene to be loaded without modifying the script.

using UnityEngine;
using UnityEngine.SceneManagement; 

public class NextLevel : MonoBehaviour
{
     [SerializeField]
     private string _level2 = "Level2";

     void OnMouseDown ()
     {
         SceneManager.LoadScene(_level2);
     }
}

It works, besides the fact that it says "The type or namespace name 'MonoBehavior' could not be found" I don't think that it is supposed to do that...