How to change scenes in Unity

17,714

Solution 1

You can use SceneManager.LoadScene which can take either the build index or the name of the Scene

if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
    SceneManager.LoadScene(0);
}

or

if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
    SceneManager.LoadScene("SceneName");
}

You just need to make sure to add all your scenes in your Build Settings.

Don't forget to import SceneManagement to be able to utilize it.

using UnityEngine.SceneManagement;

Solution 2

I think this is what you are looking for: SceneManager. Here are the docs: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html

#pragma strict
function Start() {
// Only specifying the sceneName or sceneBuildIndex will load the scene with the Single mode
SceneManager.LoadScene("OtherSceneName");
}
Share:
17,714
Admin
Author by

Admin

Updated on June 28, 2022

Comments

  • Admin
    Admin almost 2 years
        if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
        {
            //Call What Happens Here
        }
    

    I want to replace the comment with some code that will send the player to the main menu (scene 0). This is JavaScript by the way, and I am using Unity 5.6. The full code is below.

        #pragma strict
    
        var Player : Transform;
        var MoveSpeed = 4;
        var MinDist = 3;
        var MaxDist = 20;
    
        function Start()
        {
    
        }
    
        function Update ()
        {
            transform.LookAt (Player);
            if(Vector3.Distance(transform.position,Player.position) >= MinDist)
            {
                transform.position += transform.forward * MoveSpeed*Time.deltaTime;
    
                if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
                {
                    //Call What Happens Here
                }
            }
        }