Unity 场景加载管理类:异步与同步加载实现

介绍一个简单的 Unity 场景加载管理类 LoadSceneManager,该类使用单例模式,提供异步和同步两种场景加载方式,并支持异步加载进度获取。

功能特点

  • 单例模式: 确保整个场景中只有一个实例管理场景加载,避免资源冲突。
  • 异步加载: 使用 LoadSceneManager.Instance.LoadSceneAsync 方法异步加载场景,防止游戏卡顿。
  • 同步加载: 使用 LoadSceneManager.Instance.LoadScene 方法同步加载场景,适用于简单场景或需要立即切换的情况。
  • 加载进度获取: 通过 LoadSceneManager.Instance.ProgressLoadSceneAsync 方法获取异步加载进度,方便显示加载进度条等 UI 元素。

代码示例

// LoadSceneManager.cs
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadSceneManager : MonoBehaviour
{
    public static LoadSceneManager Instance { get; private set; }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    // 异步加载场景
    public AsyncOperation LoadSceneAsync(string sceneName)
    {
        return SceneManager.LoadSceneAsync(sceneName);
    }

    // 同步加载场景
    public void LoadScene(string sceneName)
    {
        SceneManager.LoadScene(sceneName);
    }

    // 获取异步加载进度
    public float ProgressLoadSceneAsync(AsyncOperation asyncOperation)
    {
        if (asyncOperation != null)
        {
            return asyncOperation.progress;
        }

        return 0f;
    }
}

使用方法

  1. LoadSceneManager.cs 文件添加到您的 Unity 项目中。
  2. 在场景中创建一个空物体,并将 LoadSceneManager 脚本挂载到该物体上。
  3. 使用 LoadSceneManager.Instance.LoadSceneAsync("场景名称") 异步加载场景,或使用 LoadSceneManager.Instance.LoadScene("场景名称") 同步加载场景。
  4. 使用 LoadSceneManager.Instance.ProgressLoadSceneAsync(asyncOperation) 获取异步加载进度,其中 asyncOperationLoadSceneAsync 方法返回的 AsyncOperation 对象。

注意: LoadSceneManager 对象需要在第一个场景加载时就存在,并保持在所有场景中不被销毁。

rar 文件大小:24.24KB