Jesse Scott
Jesse Scott

Reputation: 41

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

Upvotes: 3

Views: 21494

Answers (2)

I.B
I.B

Reputation: 2923

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;

Upvotes: 6

pasotee
pasotee

Reputation: 348

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");
}

Upvotes: 2

Related Questions