Finding objects by specified component

Hello.

I am trying to make a custom editor window in my project, and I want to make a function that would be similar to Unity’s “Add Component” button in the Inspector:

But, I want to find all objects in scene hierarchy that contain given component.

So, essentially: I want to be able to have this kinda dropdown appear underneath a search bar in my custom editor window when something is typed in, and then select a certain component and have the system find and select all objects in scene hierarchy that have this component attached to them.

So far I’ve done a little bit of custom editor making, so I am not super experienced in this. I’ve made some buttons, object fields, etc, but this is where I’ve been stuck for a while now.

I would appreciate some help!

Thank you

(Edit)

I am sure I could figure out a way to find objects with their components, but I cannot wrap my head around how to get and search through a list of all available components in project. If Someone could tell me how to do that, that would be very helpful already.

This kind of functionality is already built into the Hierarchy window, if you type t:Rigidbody for example, any GO with a Rigidbody will come up. You can type anything you want after the t: – including your custom classes – and it will show up.

If you still need your own editor to do it, and it needs auto-complete, you’re in for quite a bit of work:

Use AssetDatabase.FindAssets(“t:MonoScript”) to find every single asset in your project that derives from MonoScript. This is going to give you every single script in your project: Components, ScriptableObjects, Editors, everything. I have absolutely no idea why you can’t use t:Component or t:MonoBehaviour but you can’t. Only t:MonoScript works.

With the colossal array of paths, you can start processing all the assets. Begin with AssetDatabase.LoadAssetAtPath(). With the script loaded, you’ll need to start using reflection to compare types and get the class names to feed into future FindAssets(“t:”) calls for your editor. Make sure you cache all of this processed data because analyzing your entire project is painfully slow. You’ll want to cache all hits and misses too, so when you hook into the “project changed” callbacks, adding and removing any scripts that have been changed won’t need to analyze the whole thing again.

EDIT: I did a bit of digging through the source, and you may be able to hook into Unity’s own internal cache through this new TypeCache – Unity - Scripting API: TypeCache – that’ll save you the first part of the processing as it should be able to find all Component derived types for you.

3 Likes