unity-game-engineunityscript

How to change scenes in Unity


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
        }
    }
}    

Solution

  • 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;