-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScriptableScene.cs
378 lines (329 loc) · 11 KB
/
ScriptableScene.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
using System.Collections;
using System.Linq;
using CHARK.ScriptableScenes.Events;
using CHARK.ScriptableScenes.Utilities;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace CHARK.ScriptableScenes
{
/// <summary>
/// Reference to a <see cref="UnityEditor.SceneAsset"/>.
/// </summary>
[CreateAssetMenu(
fileName = CreateAssetMenuConstants.BaseFileName + nameof(ScriptableScene),
menuName = CreateAssetMenuConstants.BaseMenuName + "/Scriptable Scene",
order = CreateAssetMenuConstants.BaseOrder
)]
public sealed class ScriptableScene : ScriptableObject, ISerializationCallbackReceiver
{
#if UNITY_EDITOR
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.FoldoutGroup("General", Expanded = true)]
#else
[Header("General")]
#endif
[SerializeField]
private UnityEditor.SceneAsset sceneAsset;
#endif
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.FoldoutGroup("General", Expanded = true)]
[Sirenix.OdinInspector.ReadOnly]
#else
[PropertyAttributes.ReadOnly]
#endif
[Tooltip("Path to the scene asset")]
[SerializeField]
private string scenePath;
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.FoldoutGroup("General", Expanded = true)]
#endif
[Tooltip("User-friendly name for this scene")]
[SerializeField]
private string prettyName;
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.FoldoutGroup("Features", Expanded = true)]
#else
[Header("Features")]
#endif
[Tooltip("Should this scene be activated on load?")]
[SerializeField]
private bool isActivate;
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.FoldoutGroup("Features", Expanded = true)]
#endif
[Tooltip("Should this scene persist between scene changes (never unloaded)?")]
[SerializeField]
private bool isPersist;
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.FoldoutGroup("Scene Events")]
[Sirenix.OdinInspector.InlineProperty]
[Sirenix.OdinInspector.HideLabel]
#else
[Header("Events")]
#endif
[SerializeField]
private SceneEventHandler sceneEvents = new();
/// <summary>
/// Name of this scene.
/// </summary>
public string Name
{
get
{
var trimmedPrettyName = prettyName?.Trim();
if (string.IsNullOrEmpty(trimmedPrettyName))
{
return name;
}
return trimmedPrettyName;
}
}
/// <summary>
/// Path to the scene.
/// </summary>
public string ScenePath => scenePath;
/// <summary>
/// Should this scene be activated after loading.
/// </summary>
public bool IsActivate => isActivate;
/// <summary>
/// Should this scene persist between scene loads (never unloaded, useful for setup scenes).
/// </summary>
public bool IsPersist => isPersist;
/// <summary>
/// <c>true</c> if this scene is currently loaded or <c>false</c> otherwise.
/// </summary>
public bool IsLoaded => GetScene().isLoaded;
/// <summary>
/// <c>true</c> if this scene is valid or <c>false</c> otherwise.
/// </summary>
public bool IsValid => IsValidBuildIndex();
/// <summary>
/// Event handler assigned to this scene.
/// </summary>
public ISceneEventHandler SceneEvents => sceneEvents;
#if UNITY_EDITOR
internal static ScriptableScene CreateEditor(
UnityEditor.SceneAsset asset,
string path
)
{
var scriptableScene = CreateInstance<ScriptableScene>();
scriptableScene.sceneAsset = asset;
scriptableScene.scenePath = path;
return scriptableScene;
}
#endif
private const float MaxSceneLoadProgress = 0.9f;
public void OnBeforeSerialize()
{
#if UNITY_EDITOR
UpdateScenePath();
#endif
}
public void OnAfterDeserialize()
{
}
/// <returns>
/// Routine which loads this scene.
/// </returns>
public IEnumerator LoadRoutine()
{
sceneEvents.RaiseLoadEntered(this);
if (IsLoaded == false)
{
#if UNITY_EDITOR
// When scenes are loaded in Editor, in some cases we might want to load a
// scene which is not added to build settings (e.g., during testing). So all checks
// are ignored in this case.
yield return LoadInternalRoutine();
#else
// In the player, checking (not IsValid) by build since the scene might not be
// loaded yet.
if (IsValidBuildIndex())
{
yield return LoadInternalRoutine();
}
else
{
Debug.LogWarning(
$"Cannot load scene - invalid Scene at path \"{scenePath}\"",
this
);
}
#endif
}
else
{
sceneEvents.RaiseLoadProgress(this, 1f);
}
sceneEvents.RaiseLoadExited(this);
}
/// <returns>
/// Routine which unloads this scene.
/// </returns>
public IEnumerator UnloadRoutine()
{
sceneEvents.RaiseUnloadEntered(this);
if (IsLoaded)
{
#if UNITY_EDITOR
// Same as with scene loading, in Editor we want to unload even invalid scenes.
yield return UnloadInternalRoutine();
#else
// IsValid can be called as the scene had to be loaded to get to this point.
if (IsValid)
{
yield return UnloadInternalRoutine();
}
else
{
Debug.LogWarning(
$"Cannot unload scene - invalid Scene at path \"{scenePath}\"",
this
);
}
#endif
}
sceneEvents.RaiseUnloadExited(this);
}
/// <summary>
/// Activate this scene via <see cref="SceneManager.SetActiveScene"/>.
/// </summary>
public void SetActive()
{
sceneEvents.RaiseActivateEntered(this);
#if UNITY_EDITOR
// Same as with scene loading, in Editor we want to activate invalid scenes.
SetActiveInternal();
#else
// In Player at this point the scene should have been loaded and we can call IsValid.
if (IsValid)
{
SetActiveInternal();
}
else
{
Debug.LogWarning(
$"Cannot activate scene - invalid Scene at path \"{scenePath}\"",
this
);
}
#endif
sceneEvents.RaiseActivateExited(this);
}
/// <returns>
/// <c>true</c> if this Scriptable Scene is pointing to <paramref name="otherScene"/>.
/// </returns>
public bool Equals(Scene otherScene)
{
var scene = GetScene();
return scene == otherScene;
}
#if UNITY_EDITOR
private void UpdateScenePath()
{
if (sceneAsset.TryGetSceneDetails(out var newScenePath, out _) == false)
{
return;
}
var oldScenePath = scenePath;
if (string.Equals(oldScenePath, newScenePath))
{
return;
}
scenePath = newScenePath;
UnityEditor.EditorUtility.SetDirty(this);
UnityEditor.AssetDatabase.SaveAssetIfDirty(this);
}
#endif
private IEnumerator LoadInternalRoutine()
{
var operation = StartLoadSceneOperation();
AsyncOperation StartLoadSceneOperation()
{
var parameters = new LoadSceneParameters(LoadSceneMode.Additive);
#if UNITY_EDITOR
// Allow to load scenes which are not added to Build Settings (Editor only).
return UnityEditor.SceneManagement.EditorSceneManager
.LoadSceneAsyncInPlayMode(scenePath, parameters);
#else
return SceneManager.LoadSceneAsync(scenePath, parameters);
#endif
}
while (operation.isDone == false)
{
// Scene load progress range is [0, 0.9], need to remap to [0, 1] range.
var loadProgress = Mathf.Clamp01(operation.progress / MaxSceneLoadProgress);
sceneEvents.RaiseLoadProgress(this, loadProgress);
yield return null;
}
}
private IEnumerator UnloadInternalRoutine()
{
var scene = SceneManager.GetSceneByPath(scenePath);
if (scene.IsValid() == false)
{
Debug.LogError(
$"Cannot unload scene at path \"{scenePath}\", scene is invalid",
this
);
yield break;
}
if (scene.isLoaded == false)
{
Debug.LogError(
$"Cannot unload scene at path \"{scenePath}\", scene is not loaded",
this
);
yield break;
}
yield return SceneManager.UnloadSceneAsync(scene);
}
private void SetActiveInternal()
{
var sceneByPath = SceneManager.GetSceneByPath(scenePath);
SceneManager.SetActiveScene(sceneByPath);
}
private bool IsValidBuildIndex()
{
if (string.IsNullOrWhiteSpace(scenePath))
{
return false;
}
return SceneUtility.GetBuildIndexByScenePath(scenePath) >= 0;
}
private Scene GetScene()
{
if (string.IsNullOrWhiteSpace(scenePath))
{
return new Scene
{
name = "Invalid Scene",
};
}
return SceneManager.GetSceneByPath(scenePath);
}
#if UNITY_EDITOR
private class ScenePathProcessor : UnityEditor.AssetPostprocessor
{
private static void OnPostprocessAllAssets(
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths
)
{
var scriptableScenes = UnityEditor.AssetDatabase
.FindAssets($"t:{typeof(ScriptableScene)}")
.Select(UnityEditor.AssetDatabase.GUIDToAssetPath)
.Select(UnityEditor.AssetDatabase.LoadAssetAtPath<ScriptableScene>);
foreach (var scriptableScene in scriptableScenes)
{
scriptableScene.UpdateScenePath();
}
}
}
#endif
}
}