Last active
July 10, 2023 12:45
-
-
Save acoppes/06c536aacf5b99985ec9f3a6b2a034a2 to your computer and use it in GitHub Desktop.
Unity Editor helper methods to get Prefabs with one or more specific components from the assets database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
namespace Utils.Editor | |
{ | |
public static class AssetDatabaseExt | |
{ | |
[Flags] | |
public enum FindOptions | |
{ | |
None = 0, | |
ConsiderChildren = 1 | |
} | |
public static List<T> FindAssets<T>(string[] folders = null) where T : Object | |
{ | |
var guids = AssetDatabase.FindAssets($"t:{typeof(T)}", folders); | |
return guids.Select(g => AssetDatabase.LoadAssetAtPath<T>( | |
AssetDatabase.GUIDToAssetPath(g))).ToList(); | |
} | |
public static List<GameObject> FindPrefabs<T>(FindOptions options = 0, string[] folders = null) | |
{ | |
return FindPrefabs(new []{typeof(T)}, options, folders); | |
} | |
public static List<GameObject> FindPrefabs<T1, T2>(FindOptions options = 0, string[] folders = null) | |
{ | |
return FindPrefabs(new []{typeof(T1), typeof(T2)} , options, folders); | |
} | |
public static List<GameObject> FindPrefabs<T1, T2, T3>(FindOptions options = 0, string[] folders = null) | |
{ | |
return FindPrefabs(new []{typeof(T1), typeof(T2), typeof(T3)} , options, folders); | |
} | |
public static List<GameObject> FindPrefabs(IEnumerable<Type> types, FindOptions options, string[] folders) | |
{ | |
var considerChildren = options.HasFlag(FindOptions.ConsiderChildren); | |
var guids = AssetDatabase.FindAssets("t:Prefab", folders); | |
var prefabs = guids.Select(g => AssetDatabase.LoadAssetAtPath<GameObject>( | |
AssetDatabase.GUIDToAssetPath(g))).ToList(); | |
if (considerChildren) | |
{ | |
IEnumerable<GameObject> result = prefabs; | |
// By default is the AND of all specified Types | |
foreach (var type in types) | |
{ | |
result = result.Where(p => p.GetComponentInChildren(type) != null); | |
} | |
return result.ToList(); | |
} | |
else | |
{ | |
IEnumerable<GameObject> result = prefabs; | |
// By default is the AND of all specified Types | |
foreach (var type in types) | |
{ | |
result = result.Where(p => p.GetComponent(type) != null); | |
} | |
return result.ToList(); | |
} | |
} | |
} | |
} |
Added more generic methods.
Changed options to be just a flag and added default parameters for generic methods
Added a way to get assets from specific type too
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to support multiple types and to not force T of type Component