Question by
SoylentGraham · Jun 12, 2017 at 02:39 PM ·
c#propertydrawerattributepropertyfield
With a custom attribute & drawer, how do I allow multiple attributes?
I have a custom attribute which only displays if a specified function returns true. This works great. But I cannot use it with another attribute. Only the last one is "applied"
I've tried using Order=X
and Order=Y
on the field/property/member, but this hasn't made a difference. I added AllowMultiple=true
on my attribute, and that didn't work either.
Does anyone know if I'm rendering it incorrectly, or missing an attribute on my attribute?
[Range(0.0f,1.0f)]
[ShowIf("DisplayMeFunctionName")]
public float SomeScalar = 0;
This just applies my ShowIf attrbute, not the slider. If I swap them around, I get the slider, but it never hides.
https://github.com/SoylentGraham/PopUnityCommon/blob/master/ShowIfAttribute.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
#endif
using System;
[AttributeUsage(AttributeTargets.Field,AllowMultiple=true)]
public class ShowIfAttribute : PropertyAttribute
{
public readonly string FunctionName;
public ShowIfAttribute(string _FunctionName)
{
this.FunctionName = _FunctionName;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(ShowIfAttribute))]
public class PopPlatformAttributePropertyDrawer : PropertyDrawer
{
private MethodInfo CachedEventMethodInfo = null;
bool IsVisible(System.Object TargetObject,ShowIfAttribute Attrib)
{
var TargetObjectType = TargetObject.GetType();
if (CachedEventMethodInfo == null)
CachedEventMethodInfo = TargetObjectType.GetMethod(Attrib.FunctionName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (CachedEventMethodInfo != null) {
var Result = CachedEventMethodInfo.Invoke (TargetObject, null);
var ResultType = (Result == null) ? "null" : Result.GetType ().Name;
try
{
var ResultBool = (bool)Result;
return ResultBool;
}
catch(System.Exception e) {
Debug.LogWarning ("Failed to get event " + Attrib.FunctionName + " in " + TargetObjectType + " result as bool (is " + ResultType + "); " + e.Message );
}
}
Debug.LogWarning("ShowIfAttribute: Unable to find method "+ Attrib.FunctionName + " in " + TargetObjectType);
return false;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var Attrib = (ShowIfAttribute)attribute;
var TargetObject = property.serializedObject.targetObject;
if ( IsVisible(TargetObject,Attrib)) {
//base.OnGUI (position, prop, label);
EditorGUI.PropertyField (position, property, label, true);
}
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label)
{
var Attrib = (ShowIfAttribute)attribute;
var TargetObject = property.serializedObject.targetObject;
if ( IsVisible(TargetObject,Attrib)) {
//base.OnGUI (position, prop, label);
return base.GetPropertyHeight ( property, label);
}
return 0;
}
}
#endif
Comment