Unity中的LoadScene()函数在什么时候会改变场景?

5
当您调用LoadScene()函数时,它会立即切换场景,还是仅仅表示需要更改场景? LoadScene()的文档没有说明。
我正在处理的具体示例如下:
LoadScene(levelName);
ItemBox newBox = (ItemBox)Instantiate(...);

因此,使用上述代码,新的盒子会存在于我们刚刚加载的场景中,还是会在旧场景中创建,然后在加载新关卡时被销毁。

2个回答

9

它是

 UnityEngine.SceneManagement.SceneManager.LoadScene("Gameplay");

是的,它确实可以“立即”执行 - 也就是说同步执行。

换句话说,在那行代码处“停止”,等待直到加载整个场景(即使这需要几秒钟),然后新场景开始。

不要使用你在问题中提到的旧命令。

请注意,Unity还具有异步加载的能力。它会在后台“缓慢地加载新场景”。

但是:我建议您只使用普通的“LoadScene”。最重要的是可靠性和简单性。用户根本不介意电脑花几秒钟时间来加载关卡时机器“停止”的情况。

(每次我在电视上点击“Netflix”,都需要一些时间让电视完成操作。没有人关心 - 这很正常。)

但是,如果您确实想要在后台加载,请按照以下方式进行...

public void LaunchGameRunWith(string levelCode, int stars, int diamonds)
    {
    .. analytics
    StartCoroutine(_game( levelCode, superBombs, hearts));
    }

private IEnumerator _game(string levelFileName, int stars, int diamonds)
    {
    // first, add some fake delay so it looks impressive on
    // ordinary modern machines made after 1960
    yield return new WaitForSeconds(1.5f);

    AsyncOperation ao;
    ao = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync("Gameplay");

    // here's exactly how you wait for it to load:
    while (!ao.isDone)
        {
        Debug.Log("loading " +ao.progress.ToString("n2"));
        yield return null;
        }

    // here's a confusing issue. in the new scene you have to have
    // some sort of script that controls things, perhaps "NewLap"
    NewLap newLap = Object.FindObjectOfType< NewLap >();
    Gameplay gameplay = Object.FindObjectOfType<Gameplay>();

    // this is precisely how you conceptually pass info from
    // say your "main menu scene" to "actual gameplay"...
    newLap.StarLevel = stars;
    newLap.DiamondTime = diamonds;

    newLap.ActuallyBeginRunWithLevel(levelFileName);
    }

注意:该脚本回答了当玩家在“主菜单”上点击播放后,如何将信息传递“到实际的游戏场景”的问题。


2
LoadScene实际上是同步的,而不是异步的。如果要异步加载场景,请使用LoadSceneAsync - AquaGeneral
@C.G. 顺便说一下,我添加了更多信息,祝你愉快! - Fattie
@JoeBlow 我不同意关于加载横幅的看法。它有助于知道游戏没有冻结,或者卡在哪个百分比(以便搜索)。如果我们使用同步加载,我想我们就无法做到这一点,这也是你在帖子中所说的。 - Martin Dawson
嗨@MartinMazzaDawson..要使用异步,所有所需的代码都在帖子底部给出 - Fattie
如果LoadScene是即时的,为什么我的其他Monobehaviour的Awake仍然会被调用?(我确实改变了脚本顺序,使它成为在其他Awake之前发生的第一件事)(注意:这并不值得一个“问题”,它对我来说不是一个问题。我只是觉得这很奇怪,与您的信息不符) - jeromej

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接