using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace ProjectOrganizer.EditorTools
{
///
/// Preview-first organizer for loose, project-owned assets. It never runs
/// automatically and uses AssetDatabase moves so Unity GUIDs are preserved.
///
internal sealed class ProjectOrganizerWindow : EditorWindow
{
private const string SourcePreference = "ProjectOrganizer.Source";
private const string DestinationPreference = "ProjectOrganizer.Destination";
private const string ManifestPath = "Library/ProjectOrganizerLastRun.json";
private static readonly string[] ProtectedSegments =
{
"/Editor/",
"/Gizmos/",
"/Plugins/",
"/Resources/",
"/StreamingAssets/",
"/ThirdParty/"
};
[Serializable]
private sealed class MoveRecord
{
public string source;
public string destination;
public string category;
}
[Serializable]
private sealed class MoveManifest
{
public string createdUtc;
public List moves = new List();
}
private sealed class SkippedRecord
{
public string path;
public string reason;
}
private string m_sourceFolder = "Assets/_Inbox";
private string m_destinationFolder = "Assets/Organized";
private bool m_recursive = true;
private bool m_includeScenes;
private bool m_includeScripts;
private bool m_protectSpecialFolders = true;
private Vector2 m_scroll;
private readonly List m_preview = new List();
private readonly List m_skipped = new List();
private string m_status = "Choose a project-owned source folder, then preview the proposed moves.";
private bool m_hasFreshPreview;
[MenuItem("Tools/Project Organizer")]
private static void Open()
{
ProjectOrganizerWindow window = GetWindow();
window.titleContent = new GUIContent("Project Organizer");
window.minSize = new Vector2(760f, 520f);
window.Show();
}
private void OnEnable()
{
m_sourceFolder = EditorPrefs.GetString(SourcePreference, m_sourceFolder);
m_destinationFolder = EditorPrefs.GetString(DestinationPreference, m_destinationFolder);
}
private void OnGUI()
{
EditorGUILayout.Space(8f);
EditorGUILayout.LabelField("Project Organizer", EditorStyles.boldLabel);
EditorGUILayout.HelpBox(
"This tool is opt-in. Previewing does not change the project. Confirmed moves use " +
"AssetDatabase.MoveAsset, preserving .meta files, GUIDs, and serialized Unity references.",
MessageType.Info);
DrawFolderField("Source folder", ref m_sourceFolder, SourcePreference);
DrawFolderField("Destination root", ref m_destinationFolder, DestinationPreference);
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
EditorGUI.BeginChangeCheck();
m_recursive = EditorGUILayout.ToggleLeft("Scan source recursively", m_recursive);
m_protectSpecialFolders = EditorGUILayout.ToggleLeft(
"Protect Resources, Editor, Plugins, StreamingAssets, Gizmos, and ThirdParty folders",
m_protectSpecialFolders);
m_includeScenes = EditorGUILayout.ToggleLeft("Include scene assets", m_includeScenes);
m_includeScripts = EditorGUILayout.ToggleLeft(
"Include scripts (advanced: moving across asmdef boundaries can change compilation)",
m_includeScripts);
if (EditorGUI.EndChangeCheck())
InvalidatePreview();
}
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Preview Organization", GUILayout.Height(30f)))
BuildPreview();
using (new EditorGUI.DisabledScope(!m_hasFreshPreview || m_preview.Count == 0))
{
if (GUILayout.Button("Apply Previewed Moves", GUILayout.Height(30f)))
ApplyPreview();
}
using (new EditorGUI.DisabledScope(!File.Exists(ManifestPath)))
{
if (GUILayout.Button("Undo Last Run", GUILayout.Height(30f)))
UndoLastRun();
}
}
EditorGUILayout.HelpBox(m_status, MessageType.None);
EditorGUILayout.LabelField(
$"Planned moves: {m_preview.Count} Skipped: {m_skipped.Count}",
EditorStyles.boldLabel);
m_scroll = EditorGUILayout.BeginScrollView(m_scroll);
for (int i = 0; i < m_preview.Count; ++i)
{
MoveRecord move = m_preview[i];
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
EditorGUILayout.LabelField(move.category, EditorStyles.miniBoldLabel);
EditorGUILayout.SelectableLabel(move.source, GUILayout.Height(18f));
EditorGUILayout.SelectableLabel(" -> " + move.destination, GUILayout.Height(18f));
}
}
if (m_skipped.Count > 0)
{
EditorGUILayout.Space(8f);
EditorGUILayout.LabelField("Skipped Assets", EditorStyles.boldLabel);
for (int i = 0; i < m_skipped.Count; ++i)
{
SkippedRecord skipped = m_skipped[i];
EditorGUILayout.LabelField(skipped.reason, EditorStyles.miniBoldLabel);
EditorGUILayout.SelectableLabel(skipped.path, GUILayout.Height(18f));
}
}
EditorGUILayout.EndScrollView();
}
private void DrawFolderField(string label, ref string path, string preferenceKey)
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUI.BeginChangeCheck();
path = NormalizeAssetPath(EditorGUILayout.TextField(label, path));
if (EditorGUI.EndChangeCheck())
{
EditorPrefs.SetString(preferenceKey, path);
InvalidatePreview();
}
if (GUILayout.Button("Use Selected", GUILayout.Width(100f)))
{
string selectedPath = AssetDatabase.GetAssetPath(Selection.activeObject);
if (AssetDatabase.IsValidFolder(selectedPath))
{
path = NormalizeAssetPath(selectedPath);
EditorPrefs.SetString(preferenceKey, path);
InvalidatePreview();
}
else
{
ShowNotification(new GUIContent("Select a project folder first."));
}
}
}
}
private void BuildPreview()
{
m_preview.Clear();
m_skipped.Clear();
m_hasFreshPreview = false;
string source = NormalizeAssetPath(m_sourceFolder);
string destination = NormalizeAssetPath(m_destinationFolder);
if (!ValidateFolder(source, "source") || !ValidateFolder(destination, "destination"))
return;
if (string.Equals(source, "Assets", StringComparison.OrdinalIgnoreCase))
{
m_status = "Choose a project-owned subfolder. Organizing the entire Assets root is intentionally blocked.";
return;
}
string[] guids = AssetDatabase.FindAssets(string.Empty, new[] { source });
HashSet claimedDestinations = new HashSet(StringComparer.OrdinalIgnoreCase);
bool destinationIsNestedInSource =
!string.Equals(source, destination, StringComparison.OrdinalIgnoreCase) &&
IsSameOrChild(destination, source);
for (int i = 0; i < guids.Length; ++i)
{
string assetPath = NormalizeAssetPath(AssetDatabase.GUIDToAssetPath(guids[i]));
if (string.IsNullOrEmpty(assetPath) || AssetDatabase.IsValidFolder(assetPath))
continue;
if (!m_recursive && !IsDirectChild(assetPath, source))
continue;
if (destinationIsNestedInSource && IsSameOrChild(assetPath, destination))
continue;
string skipReason = GetSkipReason(assetPath);
if (!string.IsNullOrEmpty(skipReason))
{
m_skipped.Add(new SkippedRecord { path = assetPath, reason = skipReason });
continue;
}
string category = ClassifyAsset(assetPath);
string targetFolder = destination + "/" + category;
string targetPath = targetFolder + "/" + Path.GetFileName(assetPath);
if (IsSameOrChild(assetPath, targetFolder))
continue;
if (AssetDatabase.LoadMainAssetAtPath(targetPath) != null ||
!claimedDestinations.Add(targetPath))
{
m_skipped.Add(new SkippedRecord
{
path = assetPath,
reason = "Name conflict at destination"
});
continue;
}
m_preview.Add(new MoveRecord
{
source = assetPath,
destination = targetPath,
category = category
});
}
m_preview.Sort((left, right) =>
string.Compare(left.destination, right.destination, StringComparison.OrdinalIgnoreCase));
m_hasFreshPreview = true;
m_status = m_preview.Count == 0
? "Preview complete. No safe moves are currently proposed."
: $"Preview complete. Review all {m_preview.Count} proposed moves before applying them.";
}
private void ApplyPreview()
{
if (!m_hasFreshPreview || m_preview.Count == 0)
return;
bool confirmed = EditorUtility.DisplayDialog(
"Apply Project Organization?",
$"Move {m_preview.Count} assets using Unity's GUID-preserving asset database?\n\n" +
"No files will be deleted. A rollback manifest will be written to Library.",
"Apply Moves",
"Cancel");
if (!confirmed)
return;
MoveManifest manifest = new MoveManifest
{
createdUtc = DateTime.UtcNow.ToString("O")
};
int failures = 0;
for (int i = 0; i < m_preview.Count; ++i)
EnsureFolder(Path.GetDirectoryName(m_preview[i].destination));
try
{
AssetDatabase.StartAssetEditing();
for (int i = 0; i < m_preview.Count; ++i)
{
MoveRecord move = m_preview[i];
string error = AssetDatabase.MoveAsset(move.source, move.destination);
if (string.IsNullOrEmpty(error))
{
manifest.moves.Add(new MoveRecord
{
source = move.source,
destination = move.destination,
category = move.category
});
}
else
{
++failures;
Debug.LogError($"[Project Organizer] Could not move '{move.source}': {error}");
}
}
}
finally
{
AssetDatabase.StopAssetEditing();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
File.WriteAllText(ManifestPath, JsonUtility.ToJson(manifest, true));
m_status = $"Organizer completed: {manifest.moves.Count} moved, {failures} failed. " +
"Empty folders were deliberately left untouched.";
m_preview.Clear();
m_hasFreshPreview = false;
}
private void UndoLastRun()
{
MoveManifest manifest = ReadManifest();
if (manifest == null || manifest.moves == null || manifest.moves.Count == 0)
{
m_status = "No valid organizer rollback manifest was found.";
return;
}
if (!EditorUtility.DisplayDialog(
"Undo Last Organizer Run?",
$"Move {manifest.moves.Count} assets back to their recorded source paths?",
"Undo Moves",
"Cancel"))
{
return;
}
int restored = 0;
int failures = 0;
for (int i = 0; i < manifest.moves.Count; ++i)
EnsureFolder(Path.GetDirectoryName(manifest.moves[i].source));
try
{
AssetDatabase.StartAssetEditing();
for (int i = manifest.moves.Count - 1; i >= 0; --i)
{
MoveRecord move = manifest.moves[i];
if (AssetDatabase.LoadMainAssetAtPath(move.destination) == null ||
AssetDatabase.LoadMainAssetAtPath(move.source) != null)
{
++failures;
continue;
}
string error = AssetDatabase.MoveAsset(move.destination, move.source);
if (string.IsNullOrEmpty(error))
++restored;
else
++failures;
}
}
finally
{
AssetDatabase.StopAssetEditing();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
if (failures == 0)
File.Delete(ManifestPath);
m_status = $"Rollback completed: {restored} restored, {failures} skipped or failed.";
InvalidatePreview();
}
private string GetSkipReason(string assetPath)
{
string extension = Path.GetExtension(assetPath).ToLowerInvariant();
if (!m_includeScenes && extension == ".unity")
return "Scenes are excluded";
if (!m_includeScripts &&
(extension == ".cs" || extension == ".asmdef" || extension == ".asmref"))
{
return "Scripts and assembly definitions are excluded";
}
if (m_protectSpecialFolders)
{
string comparisonPath = "/" + NormalizeAssetPath(assetPath).Trim('/') + "/";
for (int i = 0; i < ProtectedSegments.Length; ++i)
{
if (comparisonPath.IndexOf(ProtectedSegments[i], StringComparison.OrdinalIgnoreCase) >= 0)
return "Protected special-purpose folder";
}
}
return string.Empty;
}
private static string ClassifyAsset(string assetPath)
{
string extension = Path.GetExtension(assetPath).ToLowerInvariant();
string fileName = Path.GetFileNameWithoutExtension(assetPath).ToLowerInvariant();
switch (extension)
{
case ".prefab": return "Prefabs";
case ".unity": return "Scenes";
case ".anim": return "Animations/Clips";
case ".controller":
case ".overridecontroller":
case ".mask": return "Animations/Controllers";
case ".wav":
case ".mp3":
case ".ogg":
case ".aif":
case ".aiff": return ClassifyAudio(fileName);
case ".mat": return "Materials";
case ".shader":
case ".shadergraph":
case ".compute":
case ".hlsl":
case ".cginc": return "Shaders";
case ".ttf":
case ".otf":
case ".fontsettings": return "Fonts";
case ".spriteatlas":
case ".spriteatlasv2": return "Art/Sprite Atlases";
case ".playable":
case ".timeline": return "Timelines";
case ".inputactions": return "Settings/Input";
case ".physicmaterial":
case ".physicmaterial2d": return "Physics";
case ".cs":
case ".asmdef":
case ".asmref": return "Scripts";
case ".txt":
case ".json":
case ".xml":
case ".csv":
case ".bytes": return "Data/Text";
case ".png":
case ".jpg":
case ".jpeg":
case ".tga":
case ".psd":
case ".tif":
case ".tiff":
case ".bmp": return IsSprite(assetPath) ? "Art/Sprites" : "Art/Textures";
case ".asset": return ClassifyAssetFile(assetPath, fileName);
default: return "Misc";
}
}
private static string ClassifyAudio(string fileName)
{
if (ContainsAny(fileName, "music", "theme", "bgm"))
return "Audio/Music";
if (ContainsAny(fileName, "ambient", "ambience", "wind", "rain", "roomtone"))
return "Audio/Ambience";
if (ContainsAny(fileName, "voice", "dialogue", "dialog", "narration"))
return "Audio/Voice";
return "Audio/SFX";
}
private static string ClassifyAssetFile(string assetPath, string fileName)
{
Type type = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
string typeName = type != null ? type.Name.ToLowerInvariant() : string.Empty;
string semanticName = typeName + " " + fileName;
if (ContainsAny(semanticName, "ability", "skill")) return "Data/Abilities";
if (ContainsAny(semanticName, "augment")) return "Data/Augments";
if (ContainsAny(semanticName, "enemy", "monster", "boss")) return "Data/Enemies";
if (ContainsAny(semanticName, "weapon", "armor", "item", "loot")) return "Data/Items";
if (ContainsAny(semanticName, "quest", "objective")) return "Data/Quests";
if (ContainsAny(semanticName, "character", "hero", "npc")) return "Data/Characters";
if (ContainsAny(semanticName, "localization", "locale", "language")) return "Data/Localization";
if (ContainsAny(semanticName, "input", "control")) return "Settings/Input";
if (ContainsAny(semanticName, "render", "pipeline", "volume", "quality")) return "Settings/Rendering";
if (ContainsAny(semanticName, "audio", "mixer")) return "Audio/Settings";
if (ContainsAny(semanticName, "tile", "palette")) return "Art/Tiles";
return "Data/ScriptableObjects";
}
private static bool IsSprite(string assetPath)
{
TextureImporter importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;
return importer != null && importer.textureType == TextureImporterType.Sprite;
}
private static bool ContainsAny(string value, params string[] needles)
{
for (int i = 0; i < needles.Length; ++i)
{
if (value.IndexOf(needles[i], StringComparison.OrdinalIgnoreCase) >= 0)
return true;
}
return false;
}
private bool ValidateFolder(string path, string label)
{
if (!path.StartsWith("Assets", StringComparison.OrdinalIgnoreCase) ||
!AssetDatabase.IsValidFolder(path))
{
m_status = $"The {label} must be an existing folder inside Assets.";
return false;
}
return true;
}
private static void EnsureFolder(string folderPath)
{
folderPath = NormalizeAssetPath(folderPath);
if (string.IsNullOrEmpty(folderPath) || AssetDatabase.IsValidFolder(folderPath))
return;
string parent = NormalizeAssetPath(Path.GetDirectoryName(folderPath));
EnsureFolder(parent);
AssetDatabase.CreateFolder(parent, Path.GetFileName(folderPath));
}
private static MoveManifest ReadManifest()
{
try
{
return File.Exists(ManifestPath)
? JsonUtility.FromJson(File.ReadAllText(ManifestPath))
: null;
}
catch (Exception exception)
{
Debug.LogException(exception);
return null;
}
}
private void InvalidatePreview()
{
m_hasFreshPreview = false;
m_preview.Clear();
m_skipped.Clear();
}
private static bool IsDirectChild(string assetPath, string folder)
{
string parent = NormalizeAssetPath(Path.GetDirectoryName(assetPath));
return string.Equals(parent, NormalizeAssetPath(folder), StringComparison.OrdinalIgnoreCase);
}
private static bool IsSameOrChild(string path, string folder)
{
string normalizedPath = NormalizeAssetPath(path).TrimEnd('/');
string normalizedFolder = NormalizeAssetPath(folder).TrimEnd('/');
return string.Equals(normalizedPath, normalizedFolder, StringComparison.OrdinalIgnoreCase) ||
normalizedPath.StartsWith(normalizedFolder + "/", StringComparison.OrdinalIgnoreCase);
}
private static string NormalizeAssetPath(string path)
{
return string.IsNullOrWhiteSpace(path)
? string.Empty
: path.Replace('\\', '/').Trim().TrimEnd('/');
}
}
}