unity同步异步加载

在开发游戏的过程中我们可能需要切换关卡或者一些操作需要切换场景
unity给我们提供两种加载场景的形式
分别是同步加载和异步加载 这两种方法各有优缺点

同步加载

优点 :管理起来比较方便,而且资源准备好了是可以及时返回的
缺点:速度比较慢

异步加载
优点:加载比较快
缺点:调用比较麻烦,不确定什么时候资源准备完成,最好的做法也是使用回调,这样回调就会很多

下面给出一个例子

 private AsyncOperation async;
    public Text loading;
    public Text t;
     private void Start()
    {
        t.enabled = false;
        StartCoroutine(AsyncLoading());
    }
 private IEnumerator AsyncLoading()
    {
        //异步加载场景
        async = SceneManager.LoadSceneAsync(4);//跳转的场景位次
        //阻止当加载完成自动切换
        async.allowSceneActivation = false;
        //读取完毕后返回,系统会自动进入C场景
        yield return async;
    }
     private void Update()
    {
        StartCoroutine(Wait());
    }
     private IEnumerator Wait()
    {
        loading.text = "加载中。。。";
        yield return new WaitForSeconds(2f);
        loading.enabled = false;
        t.enabled = true;
        t.text = "单击任意位置继续";
    }
    public void GotoScene3()
    {
        async.allowSceneActivation = true;
    }

然后在unity中赋值 即可

欢迎大家关注我的博客 我会在这里持续更新我的学习过程

发布了72 篇原创文章 · 获赞 73 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44302602/article/details/104359504