Skip to content

Instantly share code, notes, and snippets.

@nomnomab
Created February 2, 2022 23:17
Show Gist options
  • Save nomnomab/4437e74f34524bdb69213f30ff6ac4fc to your computer and use it in GitHub Desktop.
Save nomnomab/4437e74f34524bdb69213f30ff6ac4fc to your computer and use it in GitHub Desktop.
Constrains a string field's length
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class MaxLengthAttribute : PropertyAttribute {
public readonly uint Length;
public MaxLengthAttribute(uint length) {
Length = length;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(MaxLengthAttribute))]
public class MaxLengthAttributeEditor : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType == SerializedPropertyType.String) {
MaxLengthAttribute attr = (MaxLengthAttribute)attribute;
string value = property.stringValue;
if (value.Length > attr.Length) {
value = value.Substring(0, (int)attr.Length);
property.stringValue = value;
property.serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.PropertyField(position, property, label);
}
}
#endif
@nomnomab
Copy link
Author

nomnomab commented Feb 3, 2022

Neato 👍

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