How to set max string length on a EditorGUI.TextArea
? A GUILayout.TextArea
has a maxLength
property but sadly the editor-version doesn't.
1 Answer
This proved to be a bit more tricky that I originally thought. Here is my test code :
using UnityEditor;
using UnityEngine;
public class MyWindow : EditorWindow {
string textAreastring =" ";
int stringLimit = 3;
[MenuItem("Test/My Window")]
static void Init()
{
// Get existing open window or if none, make a new one:
MyWindow window = (MyWindow)EditorWindow.GetWindow(typeof(MyWindow));
window.Show();
}
void OnGUI()
{
EditorGUI.BeginChangeCheck();
textAreastring = EditorGUI.TextArea(new Rect(0, 0, 250, 25), textAreastring);
if (EditorGUI.EndChangeCheck())
{
if (textAreastring.Length >= stringLimit)
{
textAreastring = textAreastring.Substring(0, stringLimit);
GUI.FocusControl(null);
}
}
}
}
As you can see the trick is in the EditorGUI.BeginChangeCheck();
and if (EditorGUI.EndChangeCheck())
. After we check for a change we can truncate the string anyway we want. Now the problem is this only takes affect when the window looses focus so this is why I put GUI.FocusControl(null);
at the end. Not the best solution by far but I can only come up with this on the fly. If anyone can figure out a better way please do!