Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CodeSmile-0000011110110111/f1c594397b1f90b9fb94d6ba305c04b4 to your computer and use it in GitHub Desktop.
Save CodeSmile-0000011110110111/f1c594397b1f90b9fb94d6ba305c04b4 to your computer and use it in GitHub Desktop.
Read-only field displays a calculated value in Inspector
// example usage of [ReadOnlyField] that displays a calculated/converted value
// calculated value is updated whenever underlying value(s) change(s)
using UnityEngine;
public class CalculatedFieldTest : MonoBehaviour
{
private const float TargetFramerate = 60f;
[SerializeField] private int m_Ticks;
[SerializeField] [ReadOnlyField] private float m_CalculatedSeconds;
// update calculated (read-only) value .. use math as you see fit ;)
private void OnValidate() => m_CalculatedSeconds = m_Ticks / TargetFramerate;
}
// runtime script
using UnityEngine;
public class ReadOnlyFieldAttribute : PropertyAttribute {}
// editor script (add to an "Editor" folder)
using UnityEditor;
using UnityEngine;
/// <summary>
/// Displays a field with ReadOnlyFieldAttribute as readonly in Inspector.
/// </summary>
[CustomPropertyDrawer(typeof(ReadOnlyFieldAttribute))]
public sealed class ReadOnlyFieldDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) =>
EditorGUI.GetPropertyHeight(property, label, true);
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUI.enabled = false;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = true;
}
}
@CodeSmile-0000011110110111
Copy link
Author

I hereby declare all the above code as Public Domain ;)

@CodeSmile-0000011110110111
Copy link
Author

Example:
image

Fps is set to 60. Converts "ticks" to seconds.

The ReadOnlyField(Drawer) is optional. It just prevents editing the calculated field by accident and makes it clearer that the value is calculated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment