unity异步加载

文章描述了一个在Unity中使用`AsyncOperation`实现异步场景加载的脚本,包括进度条更新和防止自动切换的控制逻辑。
摘要由CSDN通过智能技术生成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class AsyncLoadScene : MonoBehaviour
{
    public Image loadingSlider;//加载条,加载图片要为fille,选择horizontal
    private float loadingSpeed = 1;
    private float targetValue;
    private AsyncOperation operation;
    private string nextSceneName;

    private bool isOperation;  // 是否已开启异步加载协程
    
    private void Awake()
    {
        // 清一下内存空间
        Resources.UnloadUnusedAssets();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();//挂起当前线程,直到处理终结器队列的线程清空该队列为止
    }

    void Start()
    {
        Init();
        if(SceneManager.GetActiveScene().name == GameDefine.加载)
        {  
            StartCoroutine(AsynLoading());
        }
    }

    
    private void Init()
    {
        // 如果是菜单场景过来的就根据记录的场景名加载下一个场景,如果不是就加载菜单场景
        nextSceneName = FjData.GetInstance().isMenuScene ? FjData.GetInstance().nextSceneName : GameDefine.菜单;

        loadingSlider.fillAmount = 0.0f;
    }
    
    IEnumerator AsynLoading()
    {
        yield return new WaitForEndOfFrame();
        operation = SceneManager.LoadSceneAsync(nextSceneName);
        isOperation = true;
        
        //阻止当加载完成自动切换
        operation.allowSceneActivation = false;
        yield return operation;
    }
    private void Update()
    {

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

            if (targetValue != loadingSlider.fillAmount)
            {
                //插值运算
                loadingSlider.fillAmount = Mathf.Lerp(loadingSlider.fillAmount, targetValue, Time.deltaTime * loadingSpeed);
                if (Mathf.Abs(loadingSlider.fillAmount - targetValue) < 0.01f)
                {
                    loadingSlider.fillAmount = targetValue;
                }
            }

            if (((int) loadingSlider.fillAmount * 100) == 100)
            {
                operation.allowSceneActivation = true;
            }
        }
    }
    private void OnDestroy()
    {
        isOperation = false;
        StopCoroutine(AsynLoading());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值