Created
February 2, 2022 23:17
-
-
Save nomnomab/4437e74f34524bdb69213f30ff6ac4fc to your computer and use it in GitHub Desktop.
Constrains a string field's length
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neato 👍