Controlling the insertion point in a textfield

Can javascript be used to move or control the insertion point in a textfield? Can a keyboard event be created in code to move the cursor around in the textfield, perhaps as a RightArrow key event? I’m allowing the user to insert information into a textfield by clicking on button options as well as typing directly, and I need to move the insertion point in the text to the right of the new button-inserted text, to allow the user to continue typing after the new data. Many thanks.

Hello

Yes, with events :slight_smile:

Well, I did hope that it might be, naruse, and I would like to learn how to do this.

The Unity Manual and Reference guides are a bit maze-like and I can’t find guidance on triggering a keyboard event in algorithm (as opposed to just pressing a key). It’s maybe simple if you know how, but all I can find about creating a keyboard event is this in the Scripting guide:

This doesn’t seem to cover the idea of triggering a keyboard event from software. To “check if a certain key has been pressed” seems more about responding to an event than creating a keyboard event. I need a bit of practical advice,—even just a pointer to where this is covered elsewhere.

I did try using just the line

Event.KeyboardEvent (“[RightArrow]”)

in the wildly optimistic hope that something might happen but it didn’t. I don’t know, I admit, how to force focus on a particular textfield, so I’m paddling about in the dark, I suppose, looking for scripting guidance or the advice to “read this”.


  1. 0 ↩︎

You’ll notice that GUI.TextField has an optional parameter of type GUIStyle. GUIStyle has a method called DrawTextWithSelection that lets you set the selected text.

Thanks, andeeee
That’s a helpful pointer.

Has anyone actual got any code that shows this working, I’m not getting any where with how DrawTextWithSelection is supposed to be used.

I’ve found a way of sending normal keyboard characters, but not arrow keys yet…

if (addChar) {
    	addChar = false;
        var myEvent : Event = Event.KeyboardEvent ("b");
        myEvent.type = EventType.KeyDown;
        Event.current = myEvent;
}

stringToEdit = GUI.TextArea (textAreaRect, stringToEdit, 3000, inputStyle);

if (myEvent) {
        myEvent.Use();
        myEvent = null;
}

This will send the “b” character into the text area… but how to send non ascii characters has me stumped at the moment.