Skip to content

Instantly share code, notes, and snippets.

@petereichinger
Last active May 22, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petereichinger/3b6fd8062690998ebf4cca055183fa58 to your computer and use it in GitHub Desktop.
Save petereichinger/3b6fd8062690998ebf4cca055183fa58 to your computer and use it in GitHub Desktop.
Show Usages of MonoBehaviours
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
/// <summary>
/// Add the 'Show Usages' menu item which lists all usages of a script in prefabs.
/// This is useful to check if a script is still used anywhere.
/// </summary>
public static class ShowScriptUsages {
[MenuItem("Assets/Show Usages",true)]
private static bool ShowUsagesCheck()
{
if (Selection.assetGUIDs.Length != 1){
return false;
}
return GetScriptType() != null;
}
[MenuItem("Assets/Show Usages")]
private static void ShowUsages()
{
var type = GetScriptType();
foreach (var go in ShowAllAssets(type)){
var goTransform = go.transform;
var rootGO = PrefabUtility.FindPrefabRoot(go);
var rootTransform = rootGO.transform;
string pathInPrefab = string.Empty;
if (rootTransform != goTransform) {
pathInPrefab = ":" + GetPathInPrefab("",goTransform,rootTransform).TrimEnd('/');
}
Debug.Log(AssetDatabase.GetAssetPath(rootTransform)+pathInPrefab,rootGO);
}
}
private static IEnumerable<GameObject> ShowAllAssets(System.Type type)
{
foreach (var assetPath in AssetDatabase.GetAllAssetPaths()){
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
if (prefab != null){
foreach (var comp in prefab.GetComponentsInChildren(type,true)){
yield return comp.gameObject;
}
}
}
}
private static Type GetScriptType(){
string guid = Selection.assetGUIDs[0];
return AssetDatabase.LoadAssetAtPath<MonoScript>(AssetDatabase.GUIDToAssetPath(guid)).GetClass();
}
private static string GetPathInPrefab(string path, Transform go, Transform root)
{
string childPath = path + root.name+ "/";
if (root == go){
return childPath;
}
foreach (Transform child in root) {
string subPath = GetPathInPrefab(childPath, go, child);
if (subPath!=null){
return subPath;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment