1.场景管理器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneController
{
public static SceneController _instance;
public static SceneController Instance
{
get
{
if(_instance == null)
{
_instance = new SceneController();
}
return _instance;
}
}
public AsyncOperation curLoadOperation;//加载信息
//加载场景
public void LoadScene(int target)
{
//加载
curLoadOperation = SceneManager.LoadSceneAsync(target);
//显示加载界面
if (SceneLoadPanel._instance == null)
{
GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/LoadScene"));//实例化预制体加载界面
//由于ChangeScene调用到这里 LoadSceneAsync会销毁当前场景的所有游戏物体 为了保证实例化出的加载界面不被销毁,
//需要在其Awake函数中调用DontDestroyOnLoad(gameObject)方法。
}
SceneLoadPanel._instance.UpdateProcess(curLoadOperation);
}
}
2.改变场景脚本
挂载到需要改变场景的触发器物体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class ChangeScene : MonoBehaviour
{
public int targetScene;
// Start is called before the first frame update
private void OnTriggerEnter2D(Collider2D collison)
{
if(collison.tag == "Player")
{
Debug.Log("切换场景!" + targetScene);
SceneController.Instance.LoadScene(targetScene);
}
}
private void OnTriggerExit2D()
{
}
}
3.抽象单例类
因为发现很多View脚本都是单例,因此在这里抽象一个单例类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonView<T> : ViewBase where T:SingletonView<T>
{
// Start is called before the first frame update
public static T _instance;
protected virtual void Awake()
{
_instance = this as T;
//因为继承该单例脚本的类名不一样 因此采用泛型 且泛型声明为需要继承SingletonView<T>
}
// Update is called once per frame
void Update()
{
}
}
4.载入界面脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SceneLoadPanel : SingletonView<SceneLoadPanel>
{
Slider slider_process;
AsyncOperation curLoadscene; //当前加载的场景
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(gameObject);
}
void Start()
{
slider_process = transform.Find("LoadScene_bg/Slider").GetComponent<Slider>();
}
// Update is called once per frame
void Update()
{
if (curLoadscene!=null)
{
UpdateProcess(curLoadscene.progress);
}
}
//更新进度条
public void UpdateProcess(float process)
{
this.Show();
this.slider_process.value = process;
if(process>=1)//场景已经加载完成
{
Invoke("Hide", 1);//延时1S隐藏
}
}
//重载 更新加载场景进度
public void UpdateProcess(AsyncOperation async)
{
curLoadscene = async;
}
public override void Hide()
{
base.Hide();
curLoadscene = null;//加载场景为空
}
}
这里将加载场景的图片和进度条做成了一个预制体。