Unity使用进度条来加载场景

A B C三个场景 开始场景 加载场景 目标场景

public void LoadNewScene()//挂在A场景(开始场景) 按钮上
{
Globe.nextSceneName = “TargetScene”;//目标场景的名字 C场景
SceneManager.LoadScene(“LoadScene”);B场景的名字 加载场景
}

public class Globe//挂在B场景上 拖个进度条 和文本
{
public static string nextSceneName;
}

public class AsyncLoadScene : MonoBehaviour
{

public Slider LoadingSlider;


 public Text loadingText;


 private float loadingSpeed = 1;


 private float targetValue;


 private AsyncOperation operation;



void Start () 
  {
  LoadingSlider.value = 0.0f;
    
  if (SceneManager.GetActiveScene().name == "LoadScene")当前场景的名字 B场景
    {
        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)
    {
        //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;//当他进度为100的时候  就跳转场景
    }

}

}

你可能感兴趣的:(Unity使用进度条来加载场景)