This is my file:
ShowWhenPropertyDrawer.cs (2.8 KB)
on line 33 i tried making it so it does not add the normal spacing when it should not show the item but it still does.
this is the file in text:
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(ShowWhenAttribute))]
public class ShowWhenPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (GetIfShouldBeShown(property))
{
EditorGUI.PropertyField(position, property, label);
}
Debug.LogError("OnGUI()");
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (GetIfShouldBeShown(property))
{
Debug.LogError("ShouldBeShown");
Debug.LogError(property.propertyPath);
return EditorGUI.GetPropertyHeight(property, label);
}
else
{
Debug.LogWarning(-EditorGUIUtility.standardVerticalSpacing);
Debug.LogWarning(property.propertyPath);
return -EditorGUIUtility.standardVerticalSpacing;
}
}
private bool GetIfShouldBeShown(SerializedProperty property)
{
bool showField = false;
ShowWhenAttribute attr = (ShowWhenAttribute) this.attribute;
List<string> pathSplitUp = property.propertyPath.Split(".").ToList();
pathSplitUp = pathSplitUp.Take(pathSplitUp.Count - 1).ToList();
pathSplitUp.Add(attr.objectFieldName);
SerializedProperty objectField = property.serializedObject.FindProperty(String.Join(".", pathSplitUp));
switch (objectField.propertyType)
{
case SerializedPropertyType.Boolean:
showField = false;
foreach (object objectComparison in attr.objectComparisons)
{
if (objectField.boolValue == (bool) objectComparison)
{
showField = true;
break;
}
}
break;
case SerializedPropertyType.Enum:
string enumValue = Enum.GetValues(attr.objectComparisons[0].GetType()).GetValue(objectField.enumValueIndex).ToString();
Debug.Log(enumValue);
showField = false;
foreach (object objectComparison in attr.objectComparisons)
{
Debug.Log(objectComparison);
if (objectComparison.ToString() == enumValue)
{
showField = true;
break;
}
}
break;
default:
Debug.LogError("Only enums and booleans are supported for ShowWhen");
showField = false;
break;
}
Debug.Log(showField);
return showField;
}
}
Not sure why it doesn’t work. I remember using the same trick and it did the job.
If you can’t get it to work the way you want then I suggest overriding CreatePropertyGUI() instead of OnGUI(). You will have far more control with the new UI system.
Agree with @ChiwTheNeko, UI Toolkit is futureproof that IMGUI would have chance to be replaced. See this foundation Unity. They made that website for UI Toolkit which is a lot of usefull things to learn at.
@discobot quote
How different our lives are when we really know what is deeply important to us, and keeping that picture in mind, we manage ourselves each day to be and to do what really matters most. — Stephen Covey