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
Works as expected in Unity 2020.3 LTS ๐
At first I put it in an Editor folder to get rid of the
UNITY_EDITOR
directives, but didn't know the PropertyAttribute HAS TO live in a regular folder. So went back to a single file.Tweaked it a bunch to match a little bit more the "offical pattern". For example here the
MinAttribute
for numbers :https://github.com/Unity-Technologies/UnityCsReference/blob/e740821767d2290238ea7954457333f06e952bad/Runtime/Export/PropertyDrawer/PropertyAttribute.cs#L99
Ended up with this result :
Will refactor it later to properly split them in their respective
PropertyAttribute
&Editor/PropertyDrawer
folder/file (that would be supplied if I need more)Thanks Nomnom, you put me on the right track. Helped me achieve intended result, and jumpstart with custom editor without learning everything upfront :)