Merge pull request #74 from mackysoft/feature/use-tostring-as-label

Implement SubclassSelectorAttribute.UseToStringAsLabel
This commit is contained in:
Makihiro 2024-10-26 23:35:48 +09:00 committed by GitHub
commit 60adb3e3d3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 23 additions and 4 deletions

View File

@ -64,7 +64,7 @@ public class Example : MonoBehaviour
[SerializeReference] [SerializeReference]
public Food food3 = new Grape(); public Food food3 = new Grape();
[SerializeReference, SubclassSelector] [SerializeReference, SubclassSelector(UseToStringAsLabel = true)]
public Food foodOne = new Apple(); public Food foodOne = new Apple();
[SerializeReference, SubclassSelector] [SerializeReference, SubclassSelector]

View File

@ -42,6 +42,19 @@ namespace MackySoft.SerializeReferenceExtensions.Editor
foldoutLabelRect = EditorGUI.IndentedRect(foldoutLabelRect); foldoutLabelRect = EditorGUI.IndentedRect(foldoutLabelRect);
Rect popupPosition = EditorGUI.PrefixLabel(foldoutLabelRect, label); Rect popupPosition = EditorGUI.PrefixLabel(foldoutLabelRect, label);
#if UNITY_2021_3_OR_NEWER
// Override the label text with the ToString() of the managed reference.
var subclassSelectorAttribute = (SubclassSelectorAttribute)attribute;
if (subclassSelectorAttribute.UseToStringAsLabel && !property.hasMultipleDifferentValues)
{
object managedReferenceValue = property.managedReferenceValue;
if (managedReferenceValue != null)
{
label.text = managedReferenceValue.ToString();
}
}
#endif
// Draw the subclass selector popup. // Draw the subclass selector popup.
if (EditorGUI.DropdownButton(popupPosition, GetTypeName(property), FocusType.Keyboard)) if (EditorGUI.DropdownButton(popupPosition, GetTypeName(property), FocusType.Keyboard))
{ {

View File

@ -4,7 +4,13 @@ using UnityEngine;
/// <summary> /// <summary>
/// Attribute to specify the type of the field serialized by the SerializeReference attribute in the inspector. /// Attribute to specify the type of the field serialized by the SerializeReference attribute in the inspector.
/// </summary> /// </summary>
[AttributeUsage(AttributeTargets.Field,AllowMultiple = false)] [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public sealed class SubclassSelectorAttribute : PropertyAttribute { public sealed class SubclassSelectorAttribute : PropertyAttribute
{
#if UNITY_2021_3_OR_NEWER
// NOTE: Use managedReferenceValue getter to invoke instance method in SubclassSelectorDrawer.
public bool UseToStringAsLabel { get; set; }
#endif
} }