欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Unity实现场景加载功能

程序员文章站 2022-06-15 19:08:21
unity场景加载分为同步加载和异步加载,供大家参考,具体内容如下同步加载 loadscene首先将前置工作做好。创建一个项目工程,然后创建三个场景 loading00、loading01、loadi...

unity场景加载分为同步加载和异步加载,供大家参考,具体内容如下

同步加载 loadscene

首先将前置工作做好。
创建一个项目工程,然后创建三个场景 loading00、loading01、loading02。每个场景分别创建一个cube、sphere、capsule 。然后打开file -> build settings, 然后将创建的 loading00、loading01、loading02拖拽到scenes in build中。如下图:

Unity实现场景加载功能

然后再创建一个 loading.cs 脚本,然后写上这段代码:

using system.collections;
using system.collections.generic;
using unityengine;
using unityengine.scenemanagement;

public class loading : monobehaviour
{
    // start is called before the first frame update
    void start()
    {
     // 同步加载场景
        scenemanager.loadscene(1, loadscenemode.additive);
    }

    // update is called once per frame
    void update()
    {
        
    }
}

scenemanager.loadscene(1, loadscenemode.additive);
第一个参数是表示加载的场景序号,第二个参数是 加载场景后,是否删除旧场景。

场景序号就是在 buildsettings 中的序号如下图:

Unity实现场景加载功能

当然,第一个参数也可以写场景的路径:
scenemanager.loadscene(“scenes/loading01”, loadscenemode.additive);

using system.collections;
using system.collections.generic;
using unityengine;
using unityengine.scenemanagement;

public class loading : monobehaviour
{
    // start is called before the first frame update
    void start()
    {
     // 同步加载场景
        scenemanager.loadscene("scenes/loading01", loadscenemode.additive);
    }

    // update is called once per frame
    void update()
    {
        
    }
}

与上述代码想过是一致的。

异步加载

异步加载需要先介 asyncoperation 类

scenemanager.loadsceneasync(1, loadscenemode.additive) 这个是异步加载的函数,其参数的用法跟同步加载的用法一致,然后,返回值 是一个 as yncoperation 类。

asyncoperation 的用处:

  • asyncoperation.isdone 这个是用来判断加载是否完成。这个属性是加载完并且跳转成功后才会变成完成
  • asyncoperation.allowsceneactivation 这个是加载完后,是否允许跳转,当为false时,即使场景加载完了,也不会跳转
  • asyncoperation.progress 这个时表示加载场景的进度。实际上的值时 0 - 0.9, 当值为0.9的时候,场景就已经加载完成了。

我们要异步加载场景的话,一般都是需要用协程一起工作

代码如下:

using system.collections;
using system.collections.generic;
using unityengine;
using unityengine.scenemanagement;

public class loading : monobehaviour
{
    // start is called before the first frame update
    void start()
    {
        startcoroutine(load());
    }


    ienumerator load()
    {

        asyncoperation asyncoperation = scenemanager.loadsceneasync(1, loadscenemode.additive);

        asyncoperation.allowsceneactivation = false;    // 这里限制了跳转


        // 这里就是循环输入进度
        while(asyncoperation.progress < 0.9f)
        {
            debug.log(" progress = " + asyncoperation.progress);
        }

        asyncoperation.allowsceneactivation = true;    // 这里打开限制
        yield return null;

        if(asyncoperation.isdone)
        {
            debug.log("完成加载");
        }
    }

    // update is called once per frame
    void update()
    {
      
    }
}

异步和同步的区别

异步不会阻塞线程,可以在加载过程中继续去执行其他的一些代码,(比如同时加载进度)而同步会阻塞线程,只有加载完毕显示后才能继续执行之后的一些代码。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关标签: Unity 场景加载