场景加载简介及异步加载具体实现

一.引用

Using  UnityEngine.SceneManagement;

二.包含方法

方法LoadScene():以索引、名称为参数,加载场景

方法LoadSceneAsync():以索引、名称为参数,异步加载场景,返回AsyncOperation对象,结合协同使用

方法 UnloadScene() 卸载某一个场景

UnityEngine.AsyncOperation:表示异步加载场景的进度

属性isDone:表示是否加载完成,返回bool类型的值

属性progress:当前进度,返回float类型的值

属性allowSceneActivation:加载完成后是否自动切换到新场景,如果在场景比较小又希望看到进度条,则可以先设置成false,进度条完成后再设置成true

三.异步加载实例:

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.UI;
 5 using UnityEngine.SceneManagement;
 6 
 7 public class S2Manager : MonoBehaviour
 8 {
12 //UI进度条以
13     private Slider _proSlider;
14 //目的是对场景进行控制 获取进度值 和允许显示
15     private AsyncOperation _async;
16 //UI应该达到的进度
17     private int _currProgress;
18     //1. 获取滑动条
19     //协同加载(异步加载 不断获取进度值 经过计算赋值给滑动条)
20     // Use this for initialization
21     void Start ()
22     {
23         _currProgress = 0;
24         _async = null;
25         _proSlider = GameObject.Find("Slider").GetComponent<Slider>();
26         StartCoroutine("LoadScene");
27     }
28     
29     // Update is called once per frame
30     void Update ()
31     {
32         //目的就是现实进度
33         _proSlider.value = _currProgress / 100.0f;
34     }
35 
36     IEnumerator LoadScene()
37     {
38       //临时的进度
39         int tmp;
40         //异步加载
41         _async = SceneManager.LoadSceneAsync("S3");
42 
43         //先不显示场景 等到进度为100%的时候显示场景 必须的!!!!
44         _async.allowSceneActivation = false;
46 #region 优化进度的 
47         while (_async.progress < 0.9f)
48         {
49             //相当于滑动条应该到的位置
50             tmp = (int) _async.progress * 100;             
52             //当滑动条 < tmp 就意味着滑动条应该变化
53             while (_currProgress < tmp)
54             {
56                 ++_currProgress;
57                 yield return  new WaitForEndOfFrame();
58             }
59         }//while end   进度为90%
60 
61         tmp = 100;
62         while (_currProgress < tmp)
63         {
64 
65             ++_currProgress;
66             yield return  new WaitForEndOfFrame();
67         }
68         
69 
70 #endregion
71         //处理进度为0 ~0.9的0    
73         //进度条完成 允许显示
74         _async.allowSceneActivation = true;
75         //SceneManager.loa
76     }
77 }

 四.同步和异步:

1.同步直接怼过来 (若机器low或场景大 就会卡)
2. 1 异步 直接怼到一个中间场景(过度场景2 (显示进度条)) --> 到场景3
3. 在异步中的两个while循环没啥大作用, 目的就是优化进度条的!!!

原文地址:https://www.cnblogs.com/Future-Better/p/9829984.html