You are here

Unity3D: InputField caret position bug workaround

Submitted by Druss on Sat, 2015-07-04 02:06

If you, like me, have the (off and on) pleasure of working with Unity3D (5.1.1f1), you are probably familiar with implementing cute li'l workarounds to get around the pesky li'l niggles that seem to plague the otherwise fun package. Today, I ran into an issue with the Inputfield nGUI component. From the looks of things, it doesn't like you playing around with its font size. As soon as you increase it, the blinking cursor (caret) starts becoming a wee wonky as, rather than being positioned in line with the text, it maintains a position slightly below the text. This has apparently been a bug for some time now.

The following is a quick hacky (C#) workaround:

float caret = -1000;

// Hack to fix caret position bug with inputfields using large fonts.
public void caretFix() {
if (caret == -1000) {
GameObject t = GameObject.Find ("Foo Input Caret");
var p = t.transform.position;
caret = p.y = p.y + 20;
t.transform.position = p;
}
}

Link this method to the Input field's On Value Changed event and you will find the cursor's vertical position fixing itself once a key has been pressed. Note however, that the cursor will be wonky until a key is pressed. The value of 20 used above will need to be tweaked depending on the size of the font being used in your input field.

If you have a plethora of input fields of varying font sizes in your project, then I wish you the very best of luck :)

Hope this helps someone out there!

Comments

I had this same problem in a couple of different projects.

The cause is that the size you're importing the TTF font is different than the size you're using it as in the text field!

Try changing the size in the TTF font importer to match the text field.

You can also import the TTF font at double size, and scale the text field to 50%, to get a higher resolution (retina) font.