Skip to content

Instantly share code, notes, and snippets.

@starikcetin
Last active November 20, 2023 20:16
Show Gist options
  • Save starikcetin/583a3b86c22efae35b5a86e9ae23f2f0 to your computer and use it in GitHub Desktop.
Save starikcetin/583a3b86c22efae35b5a86e9ae23f2f0 to your computer and use it in GitHub Desktop.
Unity get Attributes of a specific type on a SerializedProperty
using System;
using System.Reflection;
using UnityEditor;
public static class EditorUtils
{
private const BindingFlags AllBindingFlags = (BindingFlags)(-1);
/// <summary>
/// Returns attributes of type <typeparamref name="TAttribute"/> on <paramref name="serializedProperty"/>.
/// </summary>
public static TAttribute[] GetAttributes<TAttribute>(this SerializedProperty serializedProperty, bool inherit)
where TAttribute : Attribute
{
if (serializedProperty == null)
{
throw new ArgumentNullException(nameof(serializedProperty));
}
var targetObjectType = serializedProperty.serializedObject.targetObject.GetType();
if (targetObjectType == null)
{
throw new ArgumentException($"Could not find the {nameof(targetObjectType)} of {nameof(serializedProperty)}");
}
foreach (var pathSegment in serializedProperty.propertyPath.Split('.'))
{
var fieldInfo = targetObjectType.GetField(pathSegment, AllBindingFlags);
if (fieldInfo != null)
{
return (TAttribute[])fieldInfo.GetCustomAttributes<TAttribute>(inherit);
}
var propertyInfo = targetObjectType.GetProperty(pathSegment, AllBindingFlags);
if (propertyInfo != null)
{
return (TAttribute[])propertyInfo.GetCustomAttributes<TAttribute>(inherit);
}
}
throw new ArgumentException($"Could not find the field or property of {nameof(serializedProperty)}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment