【问题标题】:When does the LoadScene() function in Unity change the scene?Unity 中的 LoadScene() 函数什么时候改变场景?
【发布时间】:2016-07-16 07:46:03
【问题描述】:

当你调用函数 LoadScene() 它会立即切换场景,还是只是发出需要更改场景的信号? LoadScene() 的文档没有说。

我正在使用的具体示例如下所示:

LoadScene(levelName);
ItemBox newBox = (ItemBox)Instantiate(...);

那么使用上面的代码,newBox 会存在于我们刚刚加载的场景中,还是会在旧场景中创建,然后在加载新关卡时销毁。

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    这是

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

    是的,它“立即”执行 - 也就是说s同步。

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

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

    请注意,Unity 还可以进行a同步加载。它“在后台缓慢加载新场景”。

    但是:我鼓励您只使用普通的“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);
        }
    

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

    【讨论】:

    • 感谢您的快速回复!
    • LoadScene 实际上是同步not异步。要异步加载场景,请使用LoadSceneAsync
    • @C.G.顺便说一句,我添加了更多信息,享受吧!
    • @JoeBlow 我不同意加载横幅。知道游戏没有冻结,或者它卡在哪个百分比(谷歌它)是有用的。如果我们使用同步加载,我想我们不能有这个,这就是你在帖子中所说的。
    • 我只是偶然发现了这个很棒的答案,却没有意识到我写了它! :)
    【解决方案2】:

    也许它已经改变了。来自文档:

    使用 SceneManager.LoadScene 时,加载不会立即发生,它会在下一帧完成。

    我一直在做与海报完全相同的事情,它正在旧场景中实例化。

    https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多