Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Created July 17, 2024 15:21
Show Gist options
  • Save nekomimi-daimao/095c52671d0d78a74b99676afa0f6978 to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/095c52671d0d78a74b99676afa0f6978 to your computer and use it in GitHub Desktop.
collect dependencies in project
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Nekomimi.Daimao.Editor
{
public static class CollectDependencies
{
[MenuItem("Assets/Collect Dependencies", false, priority: 30)]
public static void CollectFromMenu()
{
var targetObject = Selection.activeObject;
if (targetObject == null)
{
Debug.LogError($"{nameof(CollectDependencies)} no file selected");
return;
}
var targetPath = AssetDatabase.GetAssetPath(targetObject);
var results = Collect(targetPath, true);
var pathResult = Path.Combine(Application.temporaryCachePath, $"{nameof(CollectDependencies)}.txt");
File.WriteAllText(pathResult, $"{targetPath}{Environment.NewLine}---{Environment.NewLine}");
File.AppendAllLines(pathResult, results);
EditorUtility.RevealInFinder(pathResult);
}
// ReSharper disable once MemberCanBePrivate.Global
public static string[] Collect(string targetPath, bool progress = false)
{
Debug.Log($"{nameof(CollectDependencies)}:{targetPath}");
var allAssets = AssetDatabase.GetAllAssetPaths()
.Where(s => s.StartsWith("Assets/"))
.Where(s => !s.EndsWith(".cs"))
.Where(File.Exists)
.ToArray();
var allAssetsLength = allAssets.Length;
var set = new HashSet<string>(allAssetsLength);
try
{
for (var i = 0; i < allAssets.Length; i++)
{
var assetPath = allAssets[i];
var dependencies = AssetDatabase.GetDependencies(assetPath, true);
if (dependencies.Contains(targetPath))
{
set.Add(assetPath);
}
if (progress)
{
var canceled = EditorUtility.DisplayCancelableProgressBar(
targetPath,
$"{i}/{allAssetsLength}",
(float)i / allAssetsLength
);
if (canceled)
{
Debug.LogWarning($"{nameof(CollectDependencies)} canceled");
return Array.Empty<string>();
}
}
}
}
finally
{
if (progress)
{
EditorUtility.ClearProgressBar();
}
}
var result = set.ToArray();
Array.Sort(result);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment