Unity 3D
Conditional Attributes

Conditional Attributes

Some of our public variables logically depends on the value of others. When some variable is unchecked (false), other variable has no meaning. For example: Player class containing canJump boolean with jumpHeight float. We don’t have to display jumpHeight when Player canJump is false etc…

cond_attr_animEven if these variables can be grouped by Header, they are still there and visible.

Imagine example script:

In the example script, the damage variable is relevant only when canDealDamage is true.

Therefore, there is no need to display the damage variable in the Inspector window, when canDealDamage is false.

To solve this, we can make our custom Property attributes and hook them with Property drawer.

Property attribute allows us to use our custom attribute in the Unity script. We will call this attribute ShowWhenAttribute.

Then we will make ShowWhenAttributeDrawer, and in the OnGUI function we will draw the property only if the referenced property is visible.

ShowWhenAttribute

This is our custom attribute, that contains 3 basic values:

  • name of the referenced variable
  • condition (optional)
  • value (optional)

simple usage:

usage with condition and value:

We can use 4 conditions:

  • Condition.Equals
  • Condition.NotEqual
  • Condition.Greater
  • Condition.Less

The variable is shown, when: <referenced_variable_value> <condition> <value>. In the provided example, the showsWhenDamageGreater5 is shown when damage is greater than 5.

[ShowWhen(“name”)] is the same as [ShowWhen(“name”, Condition.Equals, true)]

How its done

  1. the custom Property drawer (ConditionalPropertyDrawer) finds SerializedProperty of the ShowWhenAttribute
  2. from the SerializedProperty, the target object Type is found using: property.serializedObject.targetObject.GetType();
  3. using C# reflection, the FieldInfo[] of given Type is found
  4. then the SerializedProperty boolValue/floatValue/intValue/… is checked with ShowWhenAttribute values using condition for each field
  5. when the condition is not met, the OnGUI function returns immediatelly and does not draw anythnig

Supported types

  • bool
  • float
  • int
  • string
  • enum
  • object reference value

Full source code with example scene:

Edit 2022: I’ve found that my BitBucket repo has been deleted. Moved the source to the GitHub…

Available here: https://github.com/ssincak/conditional_attributes

2 thoughts on “Conditional Attributes

Comments are closed.