ScenePartition/Editor/ScenePartitionUtils.cs

94 lines
3.0 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace VertexColor.ScenePartition.Editor
{
public static class ScenePartitionUtils
{
public static string GetDataPath(ScenePartitionSO scenePartitionSO)
{
string dataPath = Path.Combine(Application.dataPath, $"../Data/Scenes/{scenePartitionSO.name}");
if (!Directory.Exists(dataPath))
{
Directory.CreateDirectory(dataPath);
}
return dataPath;
}
public static string GetScenePath(ScenePartitionSO scenePartitionSO)
{
string scenePath = AssetDatabase.GetAssetOrScenePath(scenePartitionSO.sceneAsset);
return scenePath;
}
public static void Load(ScenePartitionSO scenePartitionSO)
{
string dataPath = GetDataPath(scenePartitionSO);
string scenePath = GetScenePath(scenePartitionSO);
List<string> data = new List<string>();
List<string> files = Directory.GetFiles(dataPath).ToList();
files.Sort();
for (int i = 0; i < files.Count; i++)
{
data.AddRange(File.ReadAllLines(files[i]));
}
File.WriteAllLines(scenePath, data);
AssetDatabase.Refresh();
}
public static void Save(ScenePartitionSO scenePartitionSO)
{
string dataPath = GetDataPath(scenePartitionSO);
string scenePath = GetScenePath(scenePartitionSO);
string[] data = File.ReadAllLines(scenePath);
int lastIndex = data.Length;
for (int i = data.Length - 1; i >= 0; i--)
{
if (data[i].StartsWith("---")) // --- is the start of a new yaml document.
{
int idStartIndex = data[i].IndexOf(" &") + 2; // & is the start of the object id.
int idLength = data[i].Length;
File.WriteAllLines($"{dataPath}/{scenePartitionSO.sceneName}-{data[i][idStartIndex..idLength]}.yaml", data[i..lastIndex]);
lastIndex = i;
}
}
File.WriteAllLines($"{dataPath}/{scenePartitionSO.sceneName}.yaml", data[0..lastIndex]);
}
public static void Unload(ScenePartitionSO scenePartitionSO)
{
string dataPath = GetDataPath(scenePartitionSO);
string scenePath = GetScenePath(scenePartitionSO);
Scene scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
GameObject[] gameObjects = scene.GetRootGameObjects();
for (int i = gameObjects.Length - 1; i >= 0; i--)
{
Object.DestroyImmediate(gameObjects[i]);
}
EditorSceneManager.SaveScene(scene);
AssetDatabase.Refresh();
}
}
}