stackdev
stackdev

Reputation: 83

Filtering an object field in Unity Editor Extension

I'm looking to use Unity's ObjectField to have users search for objects of a particular type. I know the constructor allows for a typeOf(objectType), but that does not seem to allow for filtering on custom components.

Essentially, a previous editor script I have sets up objects, and places a unique custom script on each of the components, but I've been unsuccessful in utilizing the ObjectField to search for just those objects. If I change the typeOf in my object field to be my component, it is always empty, despite there being many prefabs with that script attached in my project.

Has anyone had any success with this? Using GameObject finds them, but this finds all game objects. Is there any way to restrict this? Or to keep it only looking at particular folders?

Upvotes: 3

Views: 7506

Answers (1)

ShawnFeatherly
ShawnFeatherly

Reputation: 2638

Adding a filter while the field itself stays as type Object is a bit tricky. Here's one way.

Use ShowObjectPicker

Try opening a custom ObjectPicker. To do so you'll have to hide the default object picker and call one with a set searchFilter. It is quite a bit of work.

Setting searchFilter

Use https://docs.unity3d.com/ScriptReference/EditorGUIUtility.ShowObjectPicker.html with a searchFilter that matches the component you add to every object you want to show up in an ObjectPicker. for example "t:objectType".

There's some good information on using ShowObjectPicker at https://answers.unity.com/questions/554012/how-do-i-use-editorguiutilityshowobjectpicker-c.html

Hide default object picker

Here's a post with a way to hide the default object picker Is there any way to hide the "Object picker" of an EditorGUILayout.ObjectField in Unity Isnpector?

Show picker

You'll need to create your own Editor GUI.Button to bring up the ShowObjectPicker with the custom searchFilter.

Assets searchFilter

As a sidenote, to do the same with file assets use a "l:labelName" fileFilter instead of "t:objectType". You can set the label with the Unity Editor UI as shown here: enter image description here

or with "ref:relative/path/from/assets/to/material/material.mat"

Upvotes: 2

Related Questions