Skip to content

Instantly share code, notes, and snippets.

@jfranmora
Last active November 22, 2023 16:12
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfranmora/e2d2758bd4ac0ef63d7f854571d704c8 to your computer and use it in GitHub Desktop.
Save jfranmora/e2d2758bd4ac0ef63d7f854571d704c8 to your computer and use it in GitHub Desktop.
Custom property attribute to make ReadOnly variables in Unity Inspector
using UnityEngine;
public class ReadOnlyAttribute : PropertyAttribute
{
}
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
[CanEditMultipleObjects]
public class ReadOnlyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
bool enabledState = GUI.enabled;
GUI.enabled = false;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = enabledState;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property);
}
}
@Doppelkeks
Copy link

Doppelkeks commented Nov 22, 2023

how about adding this to make it work with UI Toolkit? :)

[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
[CanEditMultipleObjects]
public class ReadOnlyDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
	EditorGUI.BeginProperty(position, label, property);

	bool enabledState = GUI.enabled;
	GUI.enabled = false;
	EditorGUI.PropertyField(position, property, label, true);
	GUI.enabled = enabledState;

	EditorGUI.EndProperty();
}

public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
	return EditorGUI.GetPropertyHeight(property);
}

public override VisualElement CreatePropertyGUI(SerializedProperty property) {
	PropertyField propertyField = new PropertyField(property);
	propertyField.SetEnabled(false);
	propertyField.style.opacity = 0.5f;
	return propertyField;
}

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