Search Unity

Question Editor Scripting with Generics

Discussion in 'Scripting' started by RyanH20, Feb 12, 2024.

  1. RyanH20

    RyanH20

    Joined:
    Jun 8, 2020
    Posts:
    23
    I'm trying to create a custom property drawer for any class that is a child of this GenericVariableSO class.

    Code (CSharp):
    1. public abstract class GenericVariableSO<T> : ScriptableObject
    2. {
    3.     [NonSerialized]
    4.     protected T runtimeValue;
    5.     [SerializeField] protected T initialValue;
    6.  
    7.     public void Set(T value)
    8.     {
    9.         runtimeValue = value;
    10.         Updated();
    11.     }
    12.  
    13.     public T Get()
    14.     {
    15.         return runtimeValue;
    16.     }
    17.  
    18. }
    All I want it to do is show the serialized object field and if that field is populated, also show the standard input field for whatever <T> field is, (and if that value is changed, save it back to the scriptable object)

    Firstly [CustomPropertyDrawer(typeof(GenericVariableSO))] does not work, it says
    Using the generic type 'GenericVariableSO<T>' requires 1 type arguments
    But [CustomPropertyDrawer(typeof(GenericVariableSO<T>))] also doesn't work,
    The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)


    So I changed it to one of the child classes just to see if I could get it working

    The child class is just empty
    Code (CSharp):
    1. public class IntVariableSO : GenericVariableSO<int>
    2. {
    3.    
    4. }
    The scriptable object field gets drawn correctly but I can't access the initialValue
    Code (CSharp):
    1. SerializedObject soProperty = new(property.objectReferenceValue);
    2. var SOInitialValueField = new PropertyField(soProperty.FindProperty("initalValue"));
    That doesn't work but no errors, so I tried to force this but
    Code (CSharp):
    1. var SOInitialValueField = ((IntVariableSO)property.objectReferenceValue).initalValue;
    throws the error: 'IntVariableSO' does not contain a definition for 'initalValue' and no accessible extension method 'initalValue' accepting a first argument of type 'IntVariableSO'

    Is there any way to resolve these issues cleanly? I'd like to keep the structure of my classes because it's nice and clean and minimal effort to create new variables but I'd also like to be able to edit the values on the monobehavior as I would if it were a regular field or property
     
  2. flashframe

    flashframe

    Joined:
    Feb 10, 2015
    Posts:
    798
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,998
    Well, you just mistyped
    "initialValue"
    . You wrote
    "initalValue"
    (so you're missing the 3rd
    i
    ).

    Unfortunately you can not use "nameof" with protected or private fields. However you could provide a readonly property which returns the field name

    Code (CSharp):
    1. public string InitialValueFieldName => nameof(initialValue);
    That way you get actual type safety n your code as you can avoid using magic string values.
    Though in order to access that value you either want to use a simple interface like

    Code (CSharp):
    1. public interface IInitialValueField
    2. {
    3.     string InitialValueFieldName { get; }
    4. }
    That way you can easily access the field name inside the property drawer, even when you're using the generic version. Since the actual property field uses reflection to shoe the proper UI, it should work fine. Though just typing the field name right would already solve the issue :)
     
    Last edited: Feb 13, 2024
    flashframe likes this.
  4. RyanH20

    RyanH20

    Joined:
    Jun 8, 2020
    Posts:
    23
    Thank you for the syntax help with the generic and the typo (I swear I copied and pasted it at least once to make sure it was right haha)

    I'm making progress, no more errors, however, I still can't get the field rendering.


    Code (CSharp):
    1. public override VisualElement CreatePropertyGUI(SerializedProperty property)
    2.     {
    3.         // Create property container element.
    4.         var container = new VisualElement();
    5.         var SOField = new PropertyField(property);
    6.  
    7.         container.Add(SOField);
    8.  
    9.         if (property.objectReferenceValue!=null)
    10.         {
    11.             SerializedObject soProperty = new(property.objectReferenceValue);
    12.             SerializedProperty prop = soProperty.GetIterator();
    13.             if(prop.NextVisible(true) )
    14.             {
    15.                 do
    16.                 {
    17.                     Debug.Log(prop.name);
    18.                 } while (prop.NextVisible(false));
    19.             }
    20.             var SOInitialValueField = new PropertyField(soProperty.FindProperty("initialValue"));
    21.             container.Add(SOInitialValueField);
    22.  
    23.         }
    24.        
    25.         return container;
    26.     }
    I've made initialValue public just for now so it can be accessed. and I've confirmed by looping that the initialValue does exist in soProperty but I'm still not getting a field to edit it.

    This is my original implementation UGUI (initialValue is called storedValue in this version), this does work but I have to create a new drawer for each type. I want to achieve the same functionality but have it just draw the correct field type without me needing to specify, plus I do like the UIToolkit's simpler syntax for adding fields too.


    Code (CSharp):
    1. using UnityEditor;
    2. using UnityEngine;
    3. using HR.Utilities.Variables;
    4.  
    5.  
    6. public abstract class CustomVariableDrawer<T> : PropertyDrawer
    7. {
    8.     protected abstract T GetValueToEdit(SerializedProperty property);
    9.     protected abstract void ApplyValue(SerializedProperty property, T newValue);
    10.  
    11.     public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    12.     {
    13.         // Adjust height as needed
    14.         return (EditorGUIUtility.singleLineHeight*2) +EditorGUIUtility.standardVerticalSpacing;
    15.     }
    16.  
    17.     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    18.     {
    19.         // Display the ScriptableObject field
    20.         EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), property, label);
    21.  
    22.         // Move the position down for the value field
    23.         position.y += EditorGUIUtility.singleLineHeight+EditorGUIUtility.standardVerticalSpacing;
    24.  
    25.         if(property.objectReferenceValue == null)
    26.         {
    27.             return;
    28.         }
    29.  
    30.         // Get the value to edit
    31.         T valueToEdit = GetValueToEdit(property);
    32.  
    33.         // Edit the value using the appropriate EditorGUI method
    34.         T newValue = EditValue(position, valueToEdit);
    35.  
    36.         // Apply the new value if changed
    37.         if (GUI.changed)
    38.         {
    39.             ApplyValue(property, newValue);
    40.             property.serializedObject.ApplyModifiedProperties();
    41.             Undo.RecordObject(property.objectReferenceValue, "Change Variable Value");
    42.             EditorUtility.SetDirty(property.objectReferenceValue);
    43.         }
    44.     }
    45.  
    46.     protected abstract T EditValue(Rect position, T valueToEdit);
    47. }
    48.  
    49. [CustomPropertyDrawer(typeof(FloatVariable))]
    50. public class FloatVariableDrawer : CustomVariableDrawer<float>
    51. {
    52.     protected override float GetValueToEdit(SerializedProperty property)
    53.     {
    54.         return ((FloatVariable)property.objectReferenceValue).storedValue;
    55.     }
    56.  
    57.     protected override void ApplyValue(SerializedProperty property, float newValue)
    58.     {
    59.         ((FloatVariable)property.objectReferenceValue).storedValue = newValue;
    60.     }
    61.  
    62.     protected override float EditValue(Rect position, float valueToEdit)
    63.     {
    64.         return EditorGUI.FloatField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), " ", valueToEdit);
    65.     }
    66. }
    67.  
    68. [CustomPropertyDrawer(typeof(IntVariable))]
    69. public class IntVariableDrawer : CustomVariableDrawer<int>
    70. {
    71.     protected override int GetValueToEdit(SerializedProperty property)
    72.     {
    73.         return ((IntVariable)property.objectReferenceValue).storedValue;
    74.     }
    75.  
    76.     protected override void ApplyValue(SerializedProperty property, int newValue)
    77.     {
    78.         ((IntVariable)property.objectReferenceValue).storedValue = newValue;
    79.     }
    80.  
    81.     protected override int EditValue(Rect position, int valueToEdit)
    82.     {
    83.         return EditorGUI.IntField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), " ", valueToEdit);
    84.     }
    85. }
    86.  
    87. [CustomPropertyDrawer(typeof(StringVariable))]
    88. public class StringVariableDrawer : CustomVariableDrawer<string>
    89. {
    90.     protected override string GetValueToEdit(SerializedProperty property)
    91.     {
    92.         return ((StringVariable)property.objectReferenceValue).storedValue;
    93.     }
    94.  
    95.     protected override void ApplyValue(SerializedProperty property, string newValue)
    96.     {
    97.         ((StringVariable)property.objectReferenceValue).storedValue = newValue;
    98.     }
    99.  
    100.     protected override string EditValue(Rect position, string valueToEdit)
    101.     {
    102.         return EditorGUI.TextField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), " ", valueToEdit);
    103.     }
    104. }
    105.  
    106. [CustomPropertyDrawer(typeof(BoolVariable))]
    107. public class BoolVariableDrawer : CustomVariableDrawer<bool>
    108. {
    109.     protected override bool GetValueToEdit(SerializedProperty property)
    110.     {
    111.         return ((BoolVariable)property.objectReferenceValue).storedValue;
    112.     }
    113.  
    114.     protected override void ApplyValue(SerializedProperty property, bool newValue)
    115.     {
    116.         ((BoolVariable)property.objectReferenceValue).storedValue = newValue;
    117.     }
    118.  
    119.     protected override bool EditValue(Rect position, bool valueToEdit)
    120.     {
    121.         return EditorGUI.Toggle(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), " ", valueToEdit);
    122.     }
    123. }
    124.  
    125.  
    126.  
     
  5. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,998
    Well, the problem here is that CreatePropertyGUI is only invoked once when the editor is shown / created. So you can not have dynamic elements like you used to in the IMGUI system. That was and still is one of the main advantages of the IMGUI system. It can react to any changes dynamically. Currently you only create your edit field when a scriptable object is assigned when the UI is created. Of course when you select an object and then assign a scriptable object, the inspector is not recreated. There are ways to play with data bindings and callbacks to achieve things like that.

    So the whole generation of the SerializedObject has to be done whenever you select / assign a new ScriptableObject instance in the inspector. Though that also means that the databinding of your edit field needs to be changed dynamically. There are probably ways with callbacks to pull that off. Though the result is probably more complicated than the IMGUI version ^^. Though maybe there's a simpler solution I'm not aware of since I haven't used the UI toolkit that often yet.

    Yout IMGUI approach would still work without the need to create concrete subclasses of your editor. When you use a EditorGUI.PropertyField it works the same way as the PropertyField class in the UI toolkit. They are type unaware / work with any serializable data that can be represented by an SerializedProperty.

    ps: This may help when you want to stick to UI Toolkit. Though note that examples are often badly designed or can be misleading.
     
    Last edited: Feb 13, 2024
  6. RyanH20

    RyanH20

    Joined:
    Jun 8, 2020
    Posts:
    23
    Thanks for the info, the code itself is definitely running because I get the debug output but good to know that it wont work properly. I'll see if the IMGUI version actually creates the field
     
  7. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,998
    Well, since your subfield essentially uses a different serializedobject as basis, you probably need to call Bind yourself. For the actual custom editor and inspected object, the inspector will do that for you once you have build your UI. Though since you essentially create a property field for a field that is not part of the inspected object, you most likely have to do the binding yourself.
     
  8. RyanH20

    RyanH20

    Joined:
    Jun 8, 2020
    Posts:
    23
    I've gone back to the IMGUI and its almost there

    Code (CSharp):
    1. [CustomPropertyDrawer(typeof(GenericVariableSO<>), true)]
    2. public class CustomVariableDrawer : PropertyDrawer
    3. {
    4.  
    5.     public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    6.     {
    7.         // Adjust height as needed
    8.         return (EditorGUIUtility.singleLineHeight * 2) + EditorGUIUtility.standardVerticalSpacing;
    9.     }
    10.     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    11.     {
    12.         EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), property, label);
    13.         position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
    14.         if (property.objectReferenceValue == null )
    15.         {
    16.             return;
    17.         }
    18.         SerializedObject soProperty = new(property.objectReferenceValue);
    19.         EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), soProperty.FindProperty("initialValue"), false);
    20.  
    21.         if (GUI.changed)
    22.         {
    23.             property.serializedObject.ApplyModifiedProperties();
    24.             Undo.RecordObject(property.objectReferenceValue, "Change Variable Value");
    25.             EditorUtility.SetDirty(property.objectReferenceValue);
    26.         }
    27.  
    28.     }
    The field exists but changes don't save. In my original version I had this just inside the if (GUI.changed) and that got the value from the field and set it on the scriptable object but I had to know the specific type to do that. I don't know how to make that last part, generic

    Code (CSharp):
    1. int newValue = EditorGUI.IntField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), " ", ((IntVariable)property.objectReferenceValue).storedValue);
    2.  
    3. ((IntVariable)property.objectReferenceValue).storedValue = newValue;
    4.  
     
  9. flashframe

    flashframe

    Joined:
    Feb 10, 2015
    Posts:
    798
    Does this work?

    Code (CSharp):
    1. ((dynamic)property.objectReferenceValue).storedValue = newValue;
     
  10. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,998
    Well, you have a second SerializedObject where you need to call "ApplyModifiedProperties" on as well. Note that your "GUI.changed" block is a mix of very different techniques and most are used wrongly.

    Undo.RecordObject must be called before the change is done. Otherwise Unity can not diff the result at the end of the UI callback.

    Calling SetDirty is kinda outdated as it just informs Unity that the actual native object has changed data and needs to be saved. However the concept of SerializedObject / SerializedProperty is that the actual serialized data is abstracted from the underlying target(s) object(s). So when you work with SerializedProperties, all changes are tracked in this abstraction layer. When you call Update on the SerializedObject, Unity will actually load / copy the actual serialized data into that abstraction layer. Now you can modify it through the SerializedProperties. Though none of the underlying objects are affected yet. Only wnen you call ApplyModifiedProperties will it actually write the changes back to the actual object(s). That's why calling SetDirty on that scriptable object instance does nothing since nothing has changed in the actual object.

    You didn'T do yourself a favour of calling your sub SerializedObject "soProperty" as it's not a property but a completely separate serialization unit.
     
  11. RyanH20

    RyanH20

    Joined:
    Jun 8, 2020
    Posts:
    23
    I actually did get it working just by changing property.serializedObject.ApplyModifiedProperties(); to soProperty.ApplyModifiedProperties(); and the undo does seem to work in the order that I have it. If I swap the applymodifiedproperties and undo, it doesn't use my undo line - it works just as if it isn't there - in that it still does the undo just without the custom text as the undo label.

    Happy to take suggestions on the name of soProperty, I'm bad at naming variables, worse when I don't really know what they are.

    This is what I've ended up with

    Code (CSharp):
    1. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    2.     {
    3.         EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), property, label);
    4.         position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
    5.         if (property.objectReferenceValue == null )
    6.         {
    7.             return;
    8.         }
    9.         SerializedObject soProperty = new(property.objectReferenceValue);
    10.         SerializedProperty initialValueProp = soProperty.FindProperty("initialValue");
    11.         EditorGUI.PropertyField(new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight), initialValueProp,new GUIContent(" ") );
    12.  
    13.  
    14.         if (GUI.changed)
    15.         {
    16.             soProperty.ApplyModifiedProperties();
    17.         }
    18.  
    19.     }
     
  12. RyanH20

    RyanH20

    Joined:
    Jun 8, 2020
    Posts:
    23
    Is there a way to take any attributes like Range or Textarea and remove them from the scriptable object field (where they're not valid) and filter them down to the initialValue field?
     
  13. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,923
    You would need to do a bunch of processing before anything is drawn, which Unity's current inspector system doesn't really support.

    Honestly, I would just get Odin Inspector. It can do all this with just a few attributes.
     
  14. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,175
    Yes, but it would be a ton of work that isn't handled for you since the property drawer is only able to see the fields that belong to the referenced type and not the field that the property drawer is rendering for. I tried playing around with ChatGPT to see how far I could get and it's just too complex of a task.

    However everything prior to this question it was able to handle just fine.

    upload_2024-2-13_18-51-39.png

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3.  
    4. [CustomPropertyDrawer(typeof(GenericVariableSO<>), true)]
    5. public class GenericVariableSODrawer : PropertyDrawer
    6. {
    7.     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    8.     {
    9.         EditorGUI.BeginProperty(position, label, property);
    10.  
    11.         // Draw the object field
    12.         var objectFieldHeight = EditorGUIUtility.singleLineHeight;
    13.         var objectFieldRect = new Rect(position.x, position.y, position.width, objectFieldHeight);
    14.         EditorGUI.PropertyField(objectFieldRect, property, label, true);
    15.  
    16.         if (property.objectReferenceValue != null)
    17.         {
    18.             SerializedObject serializedObject = new SerializedObject(property.objectReferenceValue);
    19.             SerializedProperty valueProperty = serializedObject.FindProperty("Value");
    20.  
    21.             if (valueProperty != null)
    22.             {
    23.                 EditorGUI.indentLevel++;
    24.  
    25.                 var valueFieldHeight = EditorGUI.GetPropertyHeight(valueProperty, true);
    26.                 var spacing = EditorGUIUtility.standardVerticalSpacing;
    27.                 var valueFieldRect = new Rect(position.x, position.y + objectFieldHeight + spacing, position.width, valueFieldHeight);
    28.  
    29.                 serializedObject.Update();
    30.                 EditorGUI.PropertyField(valueFieldRect, valueProperty, new GUIContent("Value"), true);
    31.                 serializedObject.ApplyModifiedProperties();
    32.  
    33.                 EditorGUI.indentLevel--;
    34.             }
    35.         }
    36.  
    37.         EditorGUI.EndProperty();
    38.     }
    39.  
    40.     public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    41.     {
    42.         if (property.objectReferenceValue != null)
    43.         {
    44.             SerializedObject serializedObject = new SerializedObject(property.objectReferenceValue);
    45.             SerializedProperty valueProperty = serializedObject.FindProperty("Value");
    46.             float valueFieldHeight = valueProperty != null ? EditorGUI.GetPropertyHeight(valueProperty, true) : 0;
    47.             return EditorGUIUtility.singleLineHeight + valueFieldHeight + EditorGUIUtility.standardVerticalSpacing;
    48.         }
    49.         else
    50.         {
    51.             return EditorGUIUtility.singleLineHeight;
    52.         }
    53.     }
    54. }

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public abstract class GenericVariableSO<T> : ScriptableObject
    4. {
    5.     public T Value;
    6. }

    Code (csharp):
    1. [CreateAssetMenu]
    2. public class IntVariableSO : GenericVariableSO<int> {}
     
  15. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,330
    Step 1: Get property attributes from the scriptable object field.
    Step 2: Figure out if any of the property drawers has a custom property drawer.
    Step 3: If so, then create the property drawer.
    Step 4: Use reflection to inject the property attribute and the FieldInfo for initialValueinto into the property drawer.
    Step 5: Draw the field using PropertyDrawer.OnGUI instead of EditorGUI.PropertyField.

    Code (CSharp):
    1. public static bool TryGetCustomPropertyDrawerForAnyAttribute(PropertyAttribute[] propertyAttributes, FieldInfo fieldToDraw, out PropertyDrawer propertyDrawer)
    2. {
    3.     foreach(var propertyAttribute in propertyAttributes)
    4.     {
    5.         if(TryGetPropertyDrawerForAttribute(propertyAttribute, fieldToDraw, out propertyDrawer))
    6.         {
    7.             return true;
    8.         }
    9.     }
    10.  
    11.     propertyDrawer = null;
    12.     return false;
    13. }
    14.  
    15. static bool TryGetCustomPropertyDrawerForAttribute(PropertyAttribute propertyAttribute, FieldInfo fieldToDraw, out PropertyDrawer propertyDrawer)
    16. {
    17.     if(!TryGetDrawerType(propertyAttribute, out Type drawerType))
    18.     {
    19.         propertyDrawer = null;
    20.         return false;
    21.     }
    22.  
    23.     propertyDrawer = CreateInstance(drawerType) as PropertyDrawer;
    24.  
    25.     if(propertyDrawer == null)
    26.     {
    27.         return false;
    28.     }
    29.  
    30.     if(propertyAttribute != null)
    31.     {
    32.         var attributeField = typeof(PropertyDrawer).GetField("m_Attribute", BindingFlags.Instance | BindingFlags.NonPublic);
    33.         attributeField.SetValue(propertyDrawer, propertyAttribute);
    34.     }
    35.  
    36.     typeof(PropertyDrawer).GetField("m_FieldInfo", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(propertyDrawer, fieldToDraw);
    37.     return true;
    38.  
    39.     static object CreateInstance(Type type)
    40.     {
    41.         try
    42.         {
    43.             return Activator.CreateInstance(type);
    44.         }
    45.         catch
    46.         {
    47.             return FormatterServices.GetUninitializedObject(type);
    48.         }
    49.     }
    50. }
    51.  
    52. static bool TryGetDrawerType(PropertyAttribute propertyAttribute, out Type drawerType)
    53. {
    54.     var propertyAttributeType = propertyAttribute.GetType();
    55.     var typeField = typeof(CustomPropertyDrawer).GetField("m_Type", BindingFlags.NonPublic | BindingFlags.Instance);
    56.     var useForChildrenField = typeof(CustomPropertyDrawer).GetField("m_UseForChildren", BindingFlags.NonPublic | BindingFlags.Instance);
    57.     drawerType = null;
    58.  
    59.     foreach(var propertyDrawerType in TypeCache.GetTypesWithAttribute<CustomPropertyDrawer>())
    60.     {
    61.         foreach(var attribute in propertyDrawerType.GetCustomAttributes<CustomPropertyDrawer>())
    62.         {
    63.             var targetType = typeField.GetValue(attribute) as Type;
    64.             if(targetType == propertyAttributeType)
    65.             {
    66.                 drawerType = propertyDrawerType;
    67.                 return true;
    68.             }
    69.  
    70.             if(targetType.IsAssignableFrom(propertyAttributeType) && (bool)useForChildrenField.GetValue(attribute))
    71.             {
    72.                 drawerType = propertyDrawerType;
    73.             }
    74.         }
    75.     }
    76.  
    77.     return drawerType != null;
    78. }
    (P.S. Suck it ChatGPT - you just got pwned!!)
     
    Last edited: Feb 14, 2024
    flashframe and Bunny83 like this.