Show When – PropertyDrawer


As we saw in the previous post about the Interval Range attribute, the Property Drawers are powerful tools that help us to modify how we show the fields on the inspector.
Today we are going to present an attribute that allows us to show or hide the fields in certain conditions. Is very useful to minimize the information that we have to see and remove some fields that we don’t need.

Software needed

We can use any Unity version and our favourite code editor.

Let’s do it

As we saw in the previous post, we begin with the class in which we define the constructors:

As we can see, all the fields that we are going to use to compare are passed through the name of the variable. We have a first constructor that we only use for the bool comparison, the second is used for all types that we admit, and the third one is only for special cases when a field can be shown depending on multiple enum values.

Below we have a small version of the drawer class that show or hide the field. In this case the bool comparison part.

First, we make sure that we have a valid comparison field. Next, we check if the passed value has the same type than the field. And then we store the comparison result in the “showField” variable. If that variable is false we don’t show the field.

But this is not enough because if we don’t override the “GetPropertyHeight” method we would see big blank spaces. So if the “showField” is false we remove the default vertical space that the inspector add.

This attribute has two problems:

1.- First, if we use an Array, we can see that the content is hidden but the name and the size not.

We can make a workaround for that encapsulating the array in a serializable class.

2.- On the other hand, Unity only can paint one Property Drawer at a time, so if we use the “Interval Range” attribute and then the “Show When” attribute we can’t see the Slider:

We’ll a solution for that in another post.

By last and as always, the full code is available here.

Leave a Reply

Your email address will not be published. Required fields are marked *