はじめに
UnityでIMEで入力したい。InputFieldとかじゃなくて。
前提
Unity 2021.3.4 f1
New Input System
Windows 10
とりあえず、Editorでの動作確認
やったこと
InputSystemのKeyboardでIME制御してみた。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
using TMPro;
public class KeyboardTest : MonoBehaviour
{
Keyboard _keyboard;
public TMP_Text m_Text;
// Start is called before the first frame update
void Start()
{
Input.imeCompositionMode = IMECompositionMode.On;
_keyboard = Keyboard.current;
_keyboard.onIMECompositionChange += OnIMECompositionChange;
_keyboard.SetIMEEnabled(true);
_keyboard.SetIMECursorPosition(new Vector2(100, 100));
}
// Update is called once per frame
void Update()
{
Debug.Log(Keyboard.current.imeSelected.isPressed);
}
private void OnIMECompositionChange(IMECompositionString compositionString)
{
Debug.Log(compositionString);
}
public void OnEnable()
{
Keyboard.current.onTextInput += OnTextInput;
}
public void OnDisable()
{
Keyboard.current.onTextInput -= OnTextInput;
}
private void OnTextInput(char c)
{
m_Text.text += c;
}
}
このスクリプトを、
このヒエラルキーを作って、EventSystemにはりつけ。
Text(TMP)の参照を設定した。
もちろん、日本語表示可能なフォントアセットを設定してある。
結果わかったこと
IME入力を有効にするには、
Input.imeCompositionMode = IMECompositionMode.On;
これがいる。
Keyboard.current.imeSelected.isPressed
は、IMEが日本語モードで文字を入力しているときに(≒IMEウインドウが出ているとき)にしかTrueにならないっぽい。
SetIMECursorPosition
とOnIMECompositionChange
は想像した通りの動きをしていた。
enterなどは、OnTextInput(char c)
には入ってこないので、別の手段で取得して、改行コードを入れるなりしてやらないといけない。
TODO
- Windowsビルドや、他のプラットフォームビルドではどのような挙動になるかの検証
- HoloLens2, Quest2 とかでどこまでこれが動くかの検証
テキストエディタ自前で作るか…