赞
踩
提醒:c#脚本知识中含有进阶知识呕
说明:开始菜单界面和加载界面是在同一个场景里,但加载界面刚开始不显示,当点击开始游戏后,激活加载界面,并同时更新滑动条进度,滑动条加载完成后,出现游戏场景
物体挂载情况:
1.playgame按钮挂载SceneChange脚本,并同时在按钮点击事件上绑定Scenechanges方法
2.CanvasLoading画布挂载Loading脚本
3.sllider在按钮点击事件上绑定CanvasLoadin物体的OnSliderProgressValueChange方法
loading.cs(更新进度条)
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class loading : MonoBehaviour { public Slider slider; public Text text_Progress; public void UpdateProgress(float progress) { slider.value = progress; } public void OnSliderProgressValueChange(float v) { text_Progress.text = string.Format("{0}%", Mathf.Round(v * 100)); } }
SceneController.cs(加载场景脚本)
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SceneController : MonoBehaviour { private int currentIndex; private Action<float> onProgressChange; private Action onFinsh; private static SceneController instance; //调用该属性,即实例化对象 public static SceneController Instance { get { if(instance==null) { GameObject obj = new GameObject("SceneController"); obj.AddComponent<SceneController>(); } return instance; } } private void Awake() { //不销毁物体,上面刚创建呢 DontDestroyOnLoad(gameObject); if (instance != null) { throw new Exception("场景里多个SceneController"); } instance = this; } public void LoadScene(int index,Action<float> onProgressChange,Action onFinsh) { this.currentIndex = index; this.onProgressChange = onProgressChange; this.onFinsh = onFinsh; StartCoroutine(LoadScene()); } private IEnumerator LoadScene() { //yield return null; //采用LoadSceneAsync异步加载,可设置进度条来更新,当场景比较大时 AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(this.currentIndex); //属性在isDone为false时,最大加载到0.9就会暂停, //直到isDone为true时才会继续加载0.9-1.0的这10% while (!asyncOperation.isDone) { //让程序等待一帧 yield return null; onProgressChange?.Invoke(asyncOperation.progress); } yield return new WaitForSeconds(1.0f); onFinsh?.Invoke(); } }
SceneChange.cs(加载界面(画布)的控制)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SceneChange : MonoBehaviour { //指定画布,要挂载loading脚本 public loading load; //场景下标 public int sceneIndex; //场景加载 public void Scenechanges() { if (load != null) { // 显示当前画布 load.gameObject.SetActive(true); } //实例化对象并通过lambad表达式传参 SceneController.Instance.LoadScene(sceneIndex, (progress) => { if (load) { //更新画布进度 load.UpdateProgress(progress); } }, () => { if (load) { //隐藏画布 load.gameObject.SetActive(false); } }); } }
效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。