Created
March 4, 2023 09:39
-
-
Save CodeSmile-0000011110110111/f1c594397b1f90b9fb94d6ba305c04b4 to your computer and use it in GitHub Desktop.
Read-only field displays a calculated value in Inspector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// runtime script | |
using UnityEngine; | |
public class ReadOnlyFieldAttribute : PropertyAttribute {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hereby declare all the above code as Public Domain ;)