I have a runtime-only object which is marked [NonSerialized], but I want it to show up in the inspector during playback for debugging/tuning.
Is there a sane way to do this? The only way I’ve found so far is to create a temporary object in the CustomEditor:
[CustomEditor(typeof(MyClass))]
public class MyClassInspector: Editor
{
[Serializable]
class MyDataHolder: ScriptableObject
{
public MyData myData;
};
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if(Application.isPlaying && MyClass.myData != null)
{
var holder = ScriptableObject.CreateInstance<MyDataHolder>();
holder.myData = MyClass.myData;
SerializedObject tempObject = new SerializedObject(holder);
SerializedProperty myData = tempObject.FindProperty("myData");
Editor e = Editor.CreateEditor(myData.objectReferenceValue);
e.DrawDefaultInspector();
DestroyObject(holder);
DestroyObject(e);
}
}
}
That works, but it’s a pretty nasty hack. It’s probably harmless in practice, but is there a less dumb way to do this?
I found this code somewhere that creates a ShowOnly attribute.
The class for the actual attribute. This can be placed anywhere
using UnityEngine;
/// <summary>
/// This will allow the use of a [ShowOnly] Attribute in scripts making a value read only in the Editor.
/// This script is complimented by one in the Editor folder that is for drawing the read only value.
/// </summary>
public class ShowOnlyAttribute : PropertyAttribute
{
}
This is the property drawer for the ShowOnly attribute. This must be placed in an Editor folder.
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(ShowOnlyAttribute))]
public class ShowOnlyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
string valueStr;
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
valueStr = prop.intValue.ToString();
break;
case SerializedPropertyType.Boolean:
valueStr = prop.boolValue.ToString();
break;
case SerializedPropertyType.Float:
valueStr = prop.floatValue.ToString("0.00000");
break;
case SerializedPropertyType.String:
valueStr = prop.stringValue;
break;
default:
if (prop.objectReferenceValue)
valueStr = prop.objectReferenceValue.name;
else
valueStr = "Not Supported!";
break;
}
EditorGUI.LabelField(position, label.text, valueStr);
}
}
You still need to setup for each Type that you want it to show, as of right now it doesn’t have much but some value types.
This is a complex class and I need to display its full inspector, but PropertyDrawers only seem to work with non-layout GUI. I don’t know any way to use GUILayout-based code inside it, like DrawDefaultInspector and OnInspectorGUI…