- Home /
Limiting EditorGUI.ObjectField() to Prefabs only?
Hey all, I'm making a EditorWindow with a few ObjectFields to let the user assign different GameObjects to each field. Some fields only allow you to assign non-scene objects, while the others can use any GameObject...that's the problem though, I want to restrict those GameObject fields to only Prefabs, that way you can assign a non-Prefab object to them.
I need to restrict those fields to only allow PrefabType.Prefab objects and not PrefabType.ModelPrefab objects. How can I get this to work? Can I do something like 'typeof(PrefabType.Prefab)' (I tried that and it doesn't like it...).
Any help would be greatly appreciated as always :)
Thanks for your time... Stephane
Answer by Kryptos · Aug 07, 2012 at 08:16 AM
Assuming your field is obj
. You can check for the type before assigning it to the field.
GameObject pObj = EditorGUI.ObjectField(new Rect(3,3,position.width - 6, 20),
"Blablabla",
obj,
typeof(GameObject));
if (pObj != null && PrefabUtility.GetPrefabType(pObj) == PrefabType.Prefab)
{
obj = pObj
}
else
{
obj = null;
}
Awesome, exactly what I needed! Thanks a lot for the quick help Nicolas!
You're welcome. Don't forget to tick the answer to keep the board clean (and up-vote if you like ;) )
Sorry about the late vote and accepted answer, I went on and implemented your solution and forgot to come back and accept your answer ;P
If you don't $$anonymous$$d, I have one more question on the same subject: Is it possible to use the Event system to detect the type of Prefab you're dragging onto the ObjectField so that you can block it before even assigning it? With your solution above, I need to create a message box to let the user know that the object which was dragged wasn't the correct type, but if you can't assign it in the first place, then there's no need to set obj = null afterwards. Does that make sense?
You can only filter by real type (i.e. $$anonymous$$onoBehaviour, GameObject) but the PrefabType is more a flag than a type. So I don't think that there is better solution to it.
You could popup a dialog window (modal) but that will be very intrusive.
That's what I though, that's too bad...but your solution is the best next choice and it will work perfectly fine :)
Thanks again!
Answer by bellicapax · Jun 20, 2017 at 09:35 PM
Just chiming in to say you can replace this now with:
_prefabToSearchFor = EditorGUILayout.ObjectField("Prefab to search for", _prefabToSearchFor, typeof(GameObject), false) as GameObject;
The "false" makes sure that you can't assign a scene object, so it must be a Prefab.