Game Development Reference
In-Depth Information
01 public void ListAllAttributes(Type t)
02 {
03 foreach(Attribute attr in t.GetCustomAttributes(true))
04 {
05 //List the type of attribute found
06 Debug.Log (attr.GetType());
07 }
08 }
The code sample 8-4 demonstrates that all attribute data can be retrieved for a given
data type in the code at runtime. This means data types and variables may have
metadata associated with them, which can be retrieved and used to further influence
how the objects should be handled. This is powerful for editor plugins because by
creating our own custom-defined attributes that can be attached to data types and
member variables, we can integrate our code with the Unity Editor without making
its logical or runtime structure invalid. That is, we can tag variables in code with
attributes to customize how they appear in the Unity Editor without invalidating or
affecting it in terms of its logic or structure at runtime. Next, we'll see how to create
custom attributes to customize the editor.
Color blending
The
Range
attribute explored previously may be attached to integer and floating-point
variables, by way of their declarations, to limit the accepted values for them between
a minimum and maximum in the Unity Editor. In the Unity Editor, a slider control is
substituted for an editable field that controls the accepted values for the variable. This
does not, of course, affect the values assigned to the same variables in the code. In the
code, at runtime, the
Range
attribute has no effect itself. Rather, the
Range
attribute
simply controls how numerical public variables are presented in the Object Inspector,
and how they are entered there via user input. Behind the scenes, an
Editor
class is
querying object
Attribute
data through reflection to control how the data type is
rendered in the Object Inspector.
The
Range
attribute works well for numbers. But it'd be great to deploy similar
behavior for other data types besides just numbers. For example, it's common to fade
between different colors, such as fading from black to transparency to create fade-in
and fade-out effects for scene transitions. This is known as Color Lerping (linear
interpolation). That is, an intermediary color is generated between two extremes
using a normalized float (between
0
and
1
).