U3D5.6 异步加载游戏场景

本文介绍如何在Unity中使用MonoBehaviour组件实现游戏场景的过渡加载,并通过UI展示加载进度。详细展示了使用SceneManager加载场景的方法,以及如何通过协程控制异步加载过程,确保加载进度的准确显示。

一、把过度场景加载出来

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class onClick : MonoBehaviour {

	// Use this for initialization
	void Start () {
        this.GetComponent<Button>().onClick.AddListener(delegate()
        {
            Debug.Log("cllick");
            SceneManager.LoadScene("loadScene");
        });
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

二、使用协程判断游戏场景是否加载完成

   

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
/// <summary>
/// 异步加载脚本
/// </summary>
public class AsyncLoadScene : MonoBehaviour
{
    public Slider loadingSlider;
    public Text loadText;

    private AsyncOperation operation;

    private int displayProgress;
    private int toProgress;

    void Start()
    {
        loadingSlider.value = 0;
        loadingSlider.maxValue = 100;

        if (SceneManager.GetActiveScene().name == "loadScene")
        {
            //启动协程  
            StartCoroutine(AsyncLoading());
        }
    }
    void Update()
    {
        Debug.Log(operation.progress);
        if (loadingSlider.value < 99)
        {
            loadingSlider.value++;
            loadText.text = "" + loadingSlider.value;
        }
        else if (operation.progress == 0.9f)
        {
            loadingSlider.value = 100;
            loadText.text = loadingSlider.value + "%";
            
            operation.allowSceneActivation = true;
        }
    }
    private IEnumerator AsyncLoading()
    {
        operation = SceneManager.LoadSceneAsync("gameScene");
        operation.allowSceneActivation = false;
        yield return operation;
    }
    private void SetLoadingPercentage(int Percentage)
    {
        loadingSlider.value = Percentage;
    }
}

当operation.allowSceneActivation为false时,operation.progress会等于0.9f直到allowSceneActivation为true再进行0.9-1的加载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值