Range with custom intervals – PropertyDrawer


Inspector classes are powerful tools but sometimes we need specific functions and more flexibility in order to show our fields in the inspector window. There is when the “Property” and “Decorator Drawers” came in.

Today we are going to show an improved version of the native Unity Range attribute that will allow us to set an interval between the consecutive numbers (for example, if we want a range between 0 and 12 with intervals of 3 in 3). Also, the attribute has the possibility to pass other variables as parameters.

Software needed

In this case, we can use any Unity version and our favourite code editor.

Let’s do it

In all “Property Drawer” the first thing to do is create our derived class from “PropertyAttribute” where we are going to define our variables and attribute parameters. There are several constructors but here we are going to see only the first, the rest of them are very similar.

As we can see, we have the usual stuff in the Range attribute, that is min and max values, but we also have the interval that we want between numbers, the precision and the precision rounding method for when we are working with floats.

Now we have to paint in a proper way the field that we have assigned the attribute.

Reviewing the class we can see that we check the field type, then we obtain the attributes values and by last we paint the slider adjusting the output value according to the interval. The last thing is very important because is one of the differences from the native Unity Range attribute.

We can see in line 40 that we are using an extension method. For that who don’t know what is it, we use extension methods in order to add functionality to an existent type without creating a derived type. As we can see the following example:

Here we can see two important things. On one hand, we must create a static class and method, and on the other hand, add the “this” modifier to the first parameter that helps us to make extension methods.

With all this seen, we have all the pieces to paint our custom Range attribute with a slider with custom intervals as we can see on the top gif.

If you want to see and use this attribute you have the full code here.

Leave a Reply

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