LoginSignup
3
1

More than 5 years have passed since last update.

[UnityEditor]TextFieldをクリアする方法

Last updated at Posted at 2017-12-13

TextFieldをクリアしたい

UnityEditorを使っていて、TextFieldやTextAreaに入力された値をクリアしたい場合があります。

ところが、素直に下記のように書いてもクリアできず、テキストが残ったままとなります。

string textFieldValue ="";

void OnGUI()
{
    textFieldValue = EditorGUILayout.TextField(textFieldValue);
    if(GUILayout.Button("クリア"))
    {
        textFieldValue = "";
    }
}

qiita1.PNG

これは、Editorでは、フォーカスが当たっているコントロールは、一度フォーカスを外さないと更新されないためとなります。なので、選択されて色が青くなっているSelectableLabelなどでも同様の現象が発生します。

対処方法

フォーカスを別のコントロールに当ててあげれば変更されます。今回はTextAreaからButtonにフォーカスを変更します。

string textFieldValue ="";

void OnGUI()
{
    textFieldValue = EditorGUILayout.TextField(textFieldValue);
    //次のコントロールに名前をつける
    GUI.SetNextControlName("ClearButton");
    if(GUILayout.Button("クリア"))
    {
        textFieldValue = "";
        //名前をつけたコントロールにフォーカスを当てる
        GUI.FocusControl("ClearButton");
    }
}

qiita2.PNG

GUI.SetNextControllNameでコントロールに名前をつけて、GUI.Focusでフォーカスを移動しています。
ただ、これだとボタンが反転した状態になるので、気になる場合は別のコントロールを作成してそこにフォーカスを当てるなどしてみてください。

以上です!

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1