Skip to content

Instantly share code, notes, and snippets.

@sttz
Created January 8, 2023 13:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sttz/702a9eadb1d2719e419d7d875f016aaf to your computer and use it in GitHub Desktop.
Save sttz/702a9eadb1d2719e419d7d875f016aaf to your computer and use it in GitHub Desktop.
Workaround for Unity 2022.2 bug where scene asset labels are removed on save
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System.IO;
/// <summary>
/// Workaround for bug: https://issuetracker.unity3d.com/issues/scene-asset-label-disappears-when-the-scene-is-saved
/// Saves the scene's label before and re-applies them after saving.
/// Will log if the labels are preserved and this workaround is no longer necessary.
/// Unfortunately, will prompt to reload the scene after saving. :(
/// </summary>
public class SceneLabelsPreserver
{
[InitializeOnLoadMethod]
static void Initialize()
{
EditorSceneManager.sceneSaving += OnSavingScene;
EditorSceneManager.sceneSaved += OnSavedScene;
}
static string currentPath;
static string[] currentLabels;
static void OnSavingScene(Scene scene, string path)
{
if (!File.Exists(path))
return;
var guid = AssetDatabase.GUIDFromAssetPath(path);
if (guid.Empty()) {
Debug.LogWarning($"SceneLabelsPreserver.OnSavingScene: Could not get GUID for scene path '{path}'");
return;
}
currentPath = path;
currentLabels = AssetDatabase.GetLabels(guid);
}
static void OnSavedScene(Scene scene)
{
if (currentPath == null || currentLabels == null || currentLabels.Length == 0)
return;
if (scene.path != currentPath) {
Debug.LogError($"SceneLabelsPreserver.OnSavedScene: Unbalanced OnSavingScene/OnSavedScene calls ({currentPath} vs {scene.path})");
return;
}
var guid = AssetDatabase.GUIDFromAssetPath(scene.path);
if (guid.Empty()) {
Debug.LogWarning($"SceneLabelsPreserver.OnSavingScene: Could not get GUID for scene path '{scene.path}'");
return;
}
var labels = AssetDatabase.GetLabels(guid);
if (labels.Length != 0) {
Debug.Log($"SceneLabelsPreserver: Scene labels appear to be preserved, maybe this fix is no longer needed? (for {scene.path})");
return;
}
var sceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset>(scene.path);
if (sceneAsset == null) {
Debug.LogError($"SceneLabelsPreserver.OnSavedScene: Could not load scene asset at path '{scene.path}'");
return;
}
AssetDatabase.SetLabels(sceneAsset, currentLabels);
AssetDatabase.SaveAssets();
currentPath = null;
currentLabels = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment