Skip to content

Instantly share code, notes, and snippets.

@mminer
Created September 28, 2021 23:16
Show Gist options
  • Save mminer/d2655d89a07511be6787e98abaebef24 to your computer and use it in GitHub Desktop.
Save mminer/d2655d89a07511be6787e98abaebef24 to your computer and use it in GitHub Desktop.
Unity function to get all properties in a SerializedObject with an attribute.
// Example usage inside Editor.OnSceneGUI for Vector3 fields:
//
// foreach (var property in GetPropertiesWithAttribute<MyCustomAttribute>(serializedObject))
// {
// Handles.Label(property.vector3Value, property.name);
// }
static IEnumerable<SerializedProperty> GetPropertiesWithAttribute<TAttribute>(SerializedObject serializedObject)
{
var targetObjectType = serializedObject.targetObject.GetType();
var property = serializedObject.GetIterator();
while (property.Next(true))
{
var field = targetObjectType.GetField(property.name);
if (field != null && Attribute.IsDefined(field, typeof(TAttribute)))
{
yield return property.Copy();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment