Unity异步加载场景与加载进度条

先上效果图

 

需要三个场景 1,2, 3

从场景1跳转到场景3,场景2是加载场景

场景1按钮的代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadName
{
    public static string LoadNameing;
}
public class LoadScence : MonoBehaviour
{
    public void Load_Btn()
    {
        LoadName.LoadNameing = "3";
        SceneManager.LoadSceneAsync("2");
    }
}

 

场景2代码如下

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

    public Text text;
    public Slider slider;
    private AsyncOperation operation;
    private float loadingSpeed = 1;
    private float targetValue=0;
    // Start is called before the first frame update
    void Start()
    {
        if (SceneManager.GetActiveScene ().name =="2")
        {
            StartCoroutine(AsyncLoading());
        }
        targetValue = 1;
    }
    IEnumerator AsyncLoading()
    {
        operation = SceneManager.LoadSceneAsync(LoadName.LoadNameing);
        operation.allowSceneActivation = false;
        yield return operation;
    }
    // Update is called once per frame
    void Update()
    {
        if (targetValue !=slider .value )
        {
            slider.value = Mathf.Lerp(slider.value, targetValue, Time.deltaTime * loadingSpeed);
          
            if (Mathf .Abs (slider.value -targetValue )<0.01f)
            {
                slider.value = targetValue;
                operation.allowSceneActivation = true;
            }
        }
        text.text = ((int)(slider.value * 100)).ToString()+"%";
      
    }
}

 

等加载完毕100%会自动跳转到场景3

 

 

本次就这么多了,有需要会在补充

 

 

 

 

 

 

 

 

posted @ 2022-04-15 14:52  剑起苍穹  阅读(681)  评论(0编辑  收藏  举报
/*鼠标点击特效*/