如何在Unity中更改场景

时间:2017-04-18 19:25:30

标签: unity3d unity5 unityscript

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

我想用一些将播放器发送到主菜单(场景0)的代码替换注释。顺便说一句,这是JavaScript,我使用的是Unity 5.6。完整的代码如下。

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

2 个答案:

答案 0 :(得分:2)

您可以使用SceneManager.LoadScene,它可以使用构建索引或场景名称

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

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

您只需确保在构建设置中添加所有场景。

不要忘记导入SceneManagement才能使用它。

import UnityEngine.SceneManagement;

答案 1 :(得分:1)

我认为这就是你要找的东西:SceneManager。以下是文档: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");
}