一个异步加载场景的脚本

24 篇文章 1 订阅
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class AsynLoad : BasePanel
{

    public static AsynLoad Instance;
    //进度条的图片
    private Image img_LoadingBar;

    private AsyncOperation m_Ao;
    //控制加载次数,只让场景加载一次
    private bool m_IsLoad = true;
    private CanvasGroup canvasGroup;
    public void Awake()
    {
        Instance = this;
        img_LoadingBar = transform.Find("imgLoadingBar").GetComponent<Image>();
        canvasGroup = this.GetComponent<CanvasGroup>();
    }
 

    /// <summary>
    /// 场景加载的方法
    /// </summary>
    public void LoadScene(string Name)
    {
         StartCoroutine("Load",Name);
    }


   /// <summary>
   /// 场景加载的协程
   /// </summary>
   /// <returns></returns>
    IEnumerator Load(string SceneName)
    {

        int displayProgress = -1;
        int toProgress = 100;
        while (displayProgress < toProgress)
        {
            displayProgress++;
            ShowProgress(displayProgress);

            if (m_IsLoad == true)
            {
                m_Ao = SceneManager.LoadSceneAsync(SceneName);
                //表示场景加载完,不让他立即跳转,等到进度条到达100再进行跳转
                m_Ao.allowSceneActivation = false;
                m_IsLoad = false;

            }
            yield return new WaitForEndOfFrame();
        }
        if (displayProgress==100)
        {
            m_Ao.allowSceneActivation = true;
            StopCoroutine("Load");
            if(MainSystem.Instance!=null)
            MainSystem.Instance.OnClosePanel();
            OnClosePanel();
        }
    }


    /// <summary>
    /// 显示进度的方法
    /// </summary>
    /// <param name="progress"></param>
    private void ShowProgress(int progress )
    {
        //注意:要将图片的Image Type属性改为 Filled,
        //添加上图片之后这个属性才能显示出来
        img_LoadingBar.fillAmount = progress * 0.01f;
    }

    public override void OnEnter()
    {


        if (canvasGroup != null)
        {
            canvasGroup.alpha = 1;
            canvasGroup.blocksRaycasts = true;

        }

       

    }

    /// <summary>
    /// 处理页面的关闭
    /// </summary>
    public override void OnExit()
    {

        canvasGroup.blocksRaycasts = false;
        canvasGroup.alpha = 0;
      
    }


    public void OnClosePanel()
    {


        UIManage.Instance.PopPanel();

    }

    public void OnDisable()
    {
        StopAllCoroutines();
    }

    public void OnDestroy()
    {
        StopAllCoroutines();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值