毕业设计之场景异步加载

       决定从一些小部分做起,与游戏整体框架无关的做起。第一个做的就是场景的异步加载了。之前并没有接触过异步加载,都是直接SceneManager.LoadScene(name);对于小场景的话没问题,但是如果场景资源太多就会造成卡顿,所以需要异步加载。

      A场景要转换到C场景,则需要一个B场景去过过渡,在B场景等待C的加载,加载完再转换到C场景。

 一共需要两个脚本:

    Globe:
 public class Globe:

{
    public static string nextSceneName="GameScene";//全局静态变量,要转换的场景名称
}
AsyncLoadScene(加载过程):

 
 
public class AsyncLoadScene : MonoBehaviour
{
    public Slider loadingSlider;  //加载进度条
    public Text loadingText;      //加载数字
    private float loadingSpeed = 1;
    private float targetValue;
    private AsyncOperation operation;

    // Use this for initialization  
    void Start()
    {
        loadingSlider.value = 0.0f;

        if (SceneManager.GetActiveScene().name == "LoadingScene")
        {
            //启动协程  
            StartCoroutine(AsyncLoading());
        }
    }

    IEnumerator AsyncLoading()
    {
        operation = SceneManager.LoadSceneAsync(Globe.nextSceneName);
        operation.allowSceneActivation = false;

        yield return operation;
    }

    void Update()
    {
        targetValue = operation.progress;

        if (operation.progress >= 0.9f)
        {
            targetValue = 1.0f;
        }

        if (targetValue != loadingSlider.value)
        {
            loadingSlider.value = Mathf.Lerp(loadingSlider.value, targetValue, Time.deltaTime * loadingSpeed);
            if (Mathf.Abs(loadingSlider.value - targetValue) < 0.01f)
            {
                loadingSlider.value = targetValue;
            }
        }

        loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%";

        if ((int)(loadingSlider.value * 100) == 100)
        {
            //允许异步加载完毕后自动切换场景  
            operation.allowSceneActivation = true;
        }
    }
}

 
 

 点击开始按钮: 
 
    //开始点击按钮
    public void StartButtonClick()
    {
        //开始按钮点击,隐藏界面,移动摄像机视角
        Logo.SetActive(false);
        StartUI.SetActive(false);
        //移动摄像机
        //canMove = true;
        //异步加载游戏场景,先加载loading场景
        SceneManager.LoadScene("LoadingScene");
        //因为到了LoadingScene场景就开始执行对于下一个场景的加载,所以要提前设置要加载场景的名字
        Globe.nextSceneName = "GameScene";
    }



 
 
参考博文:http://blog.csdn.net/qq_33747722/article/details/72582213

猜你喜欢

转载自blog.csdn.net/qq_35957011/article/details/79554970