目录
前言
无论是AB模式还是编辑器模式,都可以加载不在BuildSetting目录里的场景
编辑器加载接口,可以根据场景路径加载:
UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode("Assets/Works/Res/" + _resPath, parameters);
AB包加载接口,请注意,AB包加载的sceneName不带扩展名(.unity)
string sceneName = System.IO.Path.GetFileNameWithoutExtension(_resPath);
SceneManager.LoadSceneAsync(sceneName, parameters);
正文
ResourceManager获取SceneLoader的时候做个小改变,需要用户层传入 是Add还是Single
无论是AB包加载模式,还是Editor加载模式,要区分加载目标是资源是场景。
编辑器加载代码:EditorLoadTask,重点看Tick方法里加载目标是Scene的代码
#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EditorLoadTask:LoadTaskBase
{
/*
* 使用方式:
* "Works/Res/Prefabs/UIPanel/Canvas.prefab"
* 要带着文件扩展名
*/
public override void DoTask()
{
string path = "Assets/Works/Res/" + _loadResPath;
if (_targetType != typeof(Scene))
_target = AssetDatabase.LoadAssetAtPath(path, _targetType);
//模拟异步下一帧加载
_loadState = TaskLoadState.LoadingAsset;
}
public override void Tick()
{
if (_loadState != TaskLoadState.LoadingAsset)
return;
if (_targetType == typeof(Scene))
{
//EditorLoadTask 检查场景是否存在
Scene scene = UnityEditor.SceneManagement.EditorSceneManager.GetSceneByPath("Assets/" + _loadResPath);
if (scene == null) {
_loadState = TaskLoadState.LoadAssetFailed;
//通知ResourceLoader加载成功或失败
_callback?.Invoke(null, false);
}
else
{
_loadState = TaskLoadState.LoadAssetSuccess;
//通知ResourceLoader加载成功或失败
_callback?.Invoke(null, true);
}
}
else
{
_loadState = _target == null ? TaskLoadState.LoadAssetFailed : TaskLoadState.LoadAssetSuccess;
if (_loadState == TaskLoadState.LoadAssetFailed)
LogManager.LogError($"Failed to load asset object : path:{_loadResPath}, type:{_targetType.ToString()}");
通知Loader加载结果
_callback?.Invoke(_target, _target != null);
}
}
}
#endif
AB加载代码代码太长,在前面的文章里已经贴过源码了,这里就不再展示。